1. 程式人生 > >189. Rotate Array(三步旋轉法)

189. Rotate Array(三步旋轉法)

【題目】

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]

【分析】

採用經典的三步旋轉法:

  1. 將整個陣列 (array) 的元素前後顛倒得到array1(即:index: 0 與 index: array.length - 1)
  2. 將array1的前k個元素前後顛倒得到array2(即:index: 0 與 index: k -1)
  3. 將array2的後n - k(n為陣列元素個數)個元素前後顛倒得到array3,即最終結果

Java程式碼實現如下:

class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}