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

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

解析

这个题目的描述不是很明白,其实说白了就是将数组循环右移,题目中给的例子就是数组经过三次循环右移的结果。这种循环右移最简单的理解就是,数组最右边的一个元素移动到了数组的第一个位置,并且每一个元素向后移动一个位置。但是另外一有一种理解那就是:

未移出的元素和移出的元素分别逆序,然后再整体逆序。并且逆序这个函数实现的时间和空间复杂度都很低。

这种方法用在很多的数字对称之类的操作上。

提示:

如果循环右移的元素的个数恰好等于数组元素的个数,那么就相当于没有对数组进行任何的操作。

实现

void reverse(int nums[], int startPos, int lastPos)
{
	int temp;
	while(startPos < lastPos)
	{
		temp = nums[startPos];
		nums[startPos] = nums[lastPos];
		nums[lastPos] = temp;

		startPos++;
		lastPos--;
	}
}
void rotate(int nums[], int n, int k) 
{
	k %= n;
	if(k == 0)
	return;

	reverse(nums, n-k, n-1);
	reverse(nums, 0, n-k-1);
	reverse(nums, 0, n-1);
}

  

原文地址:https://www.cnblogs.com/stemon/p/4474382.html