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

leetcode_Rotate Array

时间:2015-05-17 16:50:29      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:rotate array

描述:

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


leetcode_Rotate Array

标签:rotate array

原文地址:http://blog.csdn.net/mnmlist/article/details/45788779

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