您的位置:首页 > 运维架构 > Linux

Rotate Array(旋转队列)

2015-03-22 18:45 176 查看


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.

Method

思想是先对分割点前后进行倒置,然后对整体数组进行倒置。
即对1,2,3,4进行倒置得到4,3,2,1。对5,6,7进行倒置得到7,6,5,
此时的数组便是4,3,2,1,7,6,5。
然后整体倒置便得到了[5,6,7,1,2,3,4]
值得注意的是LeetCode对代码的测试相对还是比较严格的,对每个算法会进行几十到几百次测试,要求全部通过
并且会进行一些非法输入值的测试。例如,本题k很明显应该小于n,但实际测试中存在k>n的情况,因此对k进行
了%n处理,实际编程中应多考虑对非法输入等特色情况的处理。

void reverse(int nums[], int n)//对数组进行倒置
{
if(n >1)
{
int i = 0;
int j = n-1;
int nTemp = 0;
for (;i < j; i++,j--)
{
nTemp = nums[i];
nums[i] = nums[j];
nums[j] = nTemp;
}
}
}

void rotate(int nums[], int n, int k) {
int nTemp = 0;
if (k > n) //对非法输入的处理
{
k = k %n;
}
if(n>=3)
{
reverse(nums, n-k);
reverse(&nums[n-k], k);
reverse(nums, n);
}
else
if(2 ==n && 1== (k%n))
{
nTemp = nums[0];
nums[0] = nums[1];
nums[1] = nTemp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息