输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
旋转法 逆转法看不懂
暴力法
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[]
}
}
}
}
额外数组
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];
}
}
}
环装替换
方法 3:使用环状替换
算法
image.png
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
网友评论