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;
}
}