代码改变世界

Leetcode - 189 Rotate Array

2017-01-14 06:53  Mux1  阅读(129)  评论(0编辑  收藏  举报

 

题目:

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.

 

分析:

这道题首先要判断k的值大于n的情况经过n次的整数倍的rotate相当于不变. 所以首先要对k求n的余数.

之后还是运用两次求逆的方法 先把整个array求逆, 之后对前k位的subaarray求逆, 剩下的subarray求逆即可达成目标.

 

代码:

public class Solution {
  public void rotate(int[] nums, int k) {
    int n = nums.length;
    if (n == 0 || k == 0){
      return;
    }

    if (k >= n) {
      k -= n;
    }

    swap(nums, 0, n - 1);
    swap(nums, 0, k - 1);
    swap(nums, k, n - 1);
}

private void swap(int[] nums, int start, int end) {
   if (start == end) {
    return;
   }
   while (start < end) {
    nums[start] = nums[start] + nums[end];
    nums[end] = nums[start] - nums[end];
    nums[start] = nums[start] - nums[end];
    start++;
    end--;
   }
  }
}