Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

轮转数组 #9

Open
Mooo-star opened this issue Feb 2, 2024 · 2 comments
Open

轮转数组 #9

Mooo-star opened this issue Feb 2, 2024 · 2 comments
Labels
算法 记录算法

Comments

@Mooo-star
Copy link
Owner

189. 轮转数组

提示
给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。

示例 1:

输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]

示例 2:

输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]

提示:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105
@Mooo-star
Copy link
Owner Author

/**
 Do not return anything, modify nums in-place instead.
 */
function rotate(nums: number[], k: number): void {
    const n = nums.length;
    const newArr = new Array(n);
    for (let i = 0; i < n; ++i) {
        newArr[(i + k) % n] = nums[i];
    }
    for (let i = 0; i < n; ++i) {
        nums[i] = newArr[i];
    }
};

@Mooo-star Mooo-star added the 算法 记录算法 label Feb 2, 2024
@sonder-ym
Copy link

/**
 Do not return anything, modify nums in-place instead.
 */
function rotate(nums: number[], k: number): void {
    const arr = [], n = nums.length;
    for (let i = 0; i < n; i++) {
        arr[(i + k) % n] = nums[i];
    }
    for (let i = 0; i < n; i++) {
        nums[i] = arr[i];
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录算法
Projects
None yet
Development

No branches or pull requests

2 participants