鍍金池/ 問答/人工智能/ 189. Rotate Array的問題?

189. Rotate Array的問題?

Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

import java.util.Arrays;

class Solution {
    public static void rotate(int[] nums, int k) {
        int[] temp = Arrays.copyOf(nums, nums.length);
        if (nums.length >= k) {
            for (int i = 0; i < nums.length; i++) {
                if (i + k > nums.length - 1) {
                    temp[i + k - nums.length] = nums[i];
                } else {
                    temp[i + k] = nums[i];
                }

            }
        }
        nums = temp;
        print(nums);
    }

    private static void print(int[] nums) {
        for (int i : nums) {
            System.out.print(i);
        }

    }

    public static void main(String[] args) {
        int[] nums = { 1, 2 };
        rotate(nums, 1);
    }
}

leetcode提交顯示:

Input:
[1,2]
1
Output:
[1,2]
Expected:
[2,1]
回答
編輯回答
魚梓

@CRIMX 已經(jīng)說的很明白了,就不贅述了,附上修改好的代碼

class Solution {
    public void rotate(int[] nums, int k) {
        int[] temp = Arrays.copyOf(nums, nums.length);
        for (int i = 0; i < nums.length; i++) {
        // 1,對調(diào)nums和temp在賦值等號左右兩邊的位置 2,用取模來處理k > nums.length的情況
            nums[(k + i)%nums.length] = temp[i];  
        }
    }
}
2017年5月1日 17:24
編輯回答
離觴

nums = temp; 替換一個局部變量的引用沒什么卵用哦

2018年6月24日 03:31