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

189. Rotate Array

时间:2018-02-22 00:41:55      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:keyword   额外   n个元素   长度   number   length   end   nbsp   ++   

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.

翻译:将有n个元素的数组向右旋转k步。

如:n=7,k=3时,数组 [1,2,3,4,5,6,7]旋转为[5,6,7,1,2,3,4]。

注意:

用尽量多的方法来解决该问题,至少有三种不同方法。

大神danny6514解法:

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

本质上来看,旋转k位,无非是把最后k位挪到最前面,作者用
k %= nums.length处理k大于数组长度的情况。
作者的思想是先全部反转,再分别把两部分(0,k-1和k,nums.length-1)反转,这样最后相当于把后面的k位挪到了前面。和我的算法相比,没有占用额外空间

class Solution {
public void rotate(int[] nums, int k) {
int[] newNum=new int[nums.length];
for (int i=0;i<nums.length;i++) {
newNum[(i+k)%nums.length]=nums[i];
}
for(int i=0;i<nums.length;i++) {
nums[i]=newNum[i];
}
}
}

 

189. Rotate Array

标签:keyword   额外   n个元素   长度   number   length   end   nbsp   ++   

原文地址:https://www.cnblogs.com/mafang/p/8457849.html

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