leetcode_Rotate Array

来源:互联网 发布:excel筛选重复数据 编辑:程序博客网 时间:2024/04/30 00:12

描述:

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]

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

思路:

当然,一个很简单且容易想到的思路就是直接循环移位k位即可,但每次都要移动n个元素,即总共需要移动k*n个元素

和Reverse Words in a String II题目类似,还有一种通过改变固定数目的元素就可以实现移位数组的功能,即先将1~len-k,len-k~len之间的元素逆置,最后将1~len之间的元素逆置,可以实现最后的旋转数组的目的。

代码:

public void rotate(int[] nums, int k) {        if(nums==null)            return;int len=nums.length;k=k%len;if(k==0)    return;int mid=len-k;int temp=0;int index=mid/2;for(int i=0;i<index;i++){    temp=nums[i];    nums[i]=nums[mid-1-i];    nums[mid-1-i]=temp;}index=(mid+len)/2;for(int i=mid;i<index;i++){    temp=nums[i];    nums[i]=nums[mid+len-1-i];    nums[mid+len-1-i]=temp;}index=len/2;for(int i=0;i<index;i++){    temp=nums[i];    nums[i]=nums[len-1-i];    nums[len-1-i]=temp;}   }


0 0
原创粉丝点击