设为首页 加入收藏

TOP

leetcode_Rotate Array
2015-11-21 01:02:00 来源: 作者: 【 】 浏览:2
Tags:leetcode_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
  
   

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇leetcode_Copy List with Random .. 下一篇[LeetCode] Symmetric Tree

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: