Skip to content

Latest commit

 

History

History
executable file
·
94 lines (83 loc) · 2.09 KB

189. Rotate Array.md

File metadata and controls

executable file
·
94 lines (83 loc) · 2.09 KB

189. Rotate Array

Question

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Thinking:

  • Method: O(N) extra space, O(N) time cost
class Solution {
    public void rotate(int[] nums, int k) {
        if(nums == null || nums.length == 0) return;
        int len = nums.length;
        k = k % len;
        int[] temp = new int[k];
        int i = len - k;
        for(; i < len; i++)
            temp[i - (len - k)] = nums[i];
        for(i = len - k - 1; i >= 0; i--)
            nums[i + k] = nums[i];
        for(i = 0; i < k; i++)
            nums[i] = temp[i];
    }
}
  • Method 2:
    • 整体反转
    • 前K反转
    • 后面反转
class Solution {
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        k %= len;
        rotate(nums, 0, len - 1);
        rotate(nums, 0, k - 1);
        rotate(nums, k, len - 1);
    }
    private void rotate(int[] nums, int left, int right){
        while(left < right){
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}

二刷

  1. 先计算余数。
  2. 保存从尾向前余数个个数。
  3. 将剩余的数向后以后。
  4. 最后将保存的数填充到数组的最开头。
class Solution {
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        int t = k % len;
        int[] arr = new int[t];
        for(int i = 0; i < t; i++){
            arr[i] = nums[len - t + i];
        }
        for(int i = len - t - 1; i >= 0; i--){
            nums[i + t] = nums[i];
        }
        for(int i = 0; i < t; i++)
            nums[i] = arr[i];
    }
}