码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode - 189 Rotate Array

时间:2017-01-14 07:56:45      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:题目   方法   tin   eve   ext   bar   ase   while   show   

 

题目:

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--;
   }
  }
}

Leetcode - 189 Rotate Array

标签:题目   方法   tin   eve   ext   bar   ase   while   show   

原文地址:http://www.cnblogs.com/mux1/p/6284593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!