首页 > 其他 > 详细

LeetCode:Rotate Array

时间:2015-05-14 18:48:01      阅读:109      评论:0      收藏:0      [点我收藏+]

题目描述:

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].


思路分析:将数组分为左右两部分,先将左右两部分各自翻转,最后再将整个数组整体翻转,即得结果。


代码:

class Solution
{
	public:
		void swap(int * a,int * b)
		{
			int temp = *a;
			*a = *b;
			*b = temp;
		}

		void rotate(vector<int> & nums,int k)
		{
			int length = nums.size();
			int l = length - (k % length);
			int r = k % length;
			for(int i = 0,j = l - 1;i < j;i++,j--)
				swap(&nums[i],&nums[j]);
			for(int i = l,j = length - 1;i < j;i++,j--)
				swap(&nums[i],&nums[j]);
			for(int i = 0,j = length - 1;i < j;i++,j--)
				swap(&nums[i],&nums[j]);
		}
};


LeetCode:Rotate Array

原文:http://blog.csdn.net/yao_wust/article/details/45722589

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!