輸入: [1,2,3,4,5,6,7] 和 k = 3
輸出: [5,6,7,1,2,3,4]
解釋:
向右旋轉(zhuǎn) 1 步: [7,1,2,3,4,5,6]
向右旋轉(zhuǎn) 2 步: [6,7,1,2,3,4,5]
向右旋轉(zhuǎn) 3 步: [5,6,7,1,2,3,4]
旋轉(zhuǎn)法 逆轉(zhuǎn)法看不懂
暴力法
public class Solution {
public void rotate(int[] nums, int k) {
int temp, previous;
for (int i = 0; i < k; i++) { //三次k
previous = nums[nums.length - 1];//取三次最后面的元素
for (int j = 0; j < nums.length; j++) { //nusmlength次
temp = nums[j];//位置交換
nums[j] = previous;
previous = temp; //nums[nums.length = nums[j[]
}
}
}
}
額外數(shù)組
public class Solution {
public void rotate(int[] nums, int k) {
int[] a = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
a[(i + k) % nums.length] = nums[i]; // 超過length 開始取0 1 2
}
for (int i = 0; i < nums.length; i++) {
nums[i] = a[i];
}
}
}
環(huán)裝替換
方法 3:使用環(huán)狀替換
算法
nums: [1, 2, 3, 4, 5, 6]
k: 2
public class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int count = 0;
for (int start = 0; count < nums.length; start++) {
int current = start;
int prev = nums[start];
do {
int next = (current + k) % nums.length;
int temp = nums[next];
nums[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);
}
}
}
作者:LeetCode
鏈接:https://leetcode-cn.com/problems/rotate-array/solution/xuan-zhuan-shu-zu-by-leetcode/
來源:力扣(LeetCode)
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán)酱塔,非商業(yè)轉(zhuǎn)載請注明出處岂傲。