/**
* 旋轉數組:將數組的後 k 位數移至頭部,前 length - k 位數移至尾部
* 要求使用原地算法,即不使用額外的空間
* @param nums 數組
* @param k 旋轉的個數
*/
private static void rotate(int[] nums, int k) {
int length = nums.length;
// 無須操作
if (k == 0 || k == length || length == 1) {
return;
}
// 修正 k
if (k > length) {
k %= length;
}
// 從 length - 1 開始
int indexLimit = length - 1;
int curIndex = indexLimit;
int lastIndex = indexLimit;
int lastValue = nums[indexLimit];
int count = 0;
while (count++ < length) {
curIndex += k;
// 修正 curIndex
if (curIndex > indexLimit) {
curIndex -= length;
}
int tmp = nums[curIndex];
nums[curIndex] = lastValue;
lastValue = tmp;
if (curIndex == lastIndex) {
// 一次完整的迭代交換後
// 需要重置索引和 lastValue
curIndex = --lastIndex;
lastValue = nums[curIndex];
}
}
}
leetcode - 189. 旋轉數組
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.