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;
}
}
相关文章推荐
- leetcode 189. Rotate Array-旋转数组
- Rotate Array 数组的旋转
- 面试_java:数组:旋转数组:rotate array(189)
- leetcode 189. Rotate Array旋转数组
- leetcode_189. Rotate Array 原地旋转数组
- Rotate Array数组旋转
- LeetCode Rotate Array(数组的旋转)
- leetcode Rotate Array 旋转数组
- [LeetCode] 189. Rotate Array 旋转数组
- 【LeetCode】Rotate Array 旋转数组
- rotate array 旋转数组
- [LeetCode]12. Rotate Array旋转数组
- LeetCode 189. Rotate Array (旋转数组)
- LeetCode 189. Rotate Array(旋转数组)
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode Rotate Array 旋转数组
- Rotate Array 数组旋转 leetcode
- LeetCode 189 Rotate Array(旋转数组)
- 189. Rotate Array (旋转数组)
- leetcode:Rotate Array旋转数组