题目:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [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]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的原地算法。
学习:代码来自Leetcode.solution
public class Solution {
public void rotate(int[] nums, int k) {
int temp, previous;
for (int i = 0; i < k; i++) {
previous = nums[nums.length - 1]; //for i 运行k次,每一次,previous都等于nums的最后一个元素
for (int j = 0; j < nums.length; j++) {//for j运行数组nums的长度次,每一次,把nums[]的最后一个元素向前
temp = nums[j];
nums[j] = previous;
previous = temp;
}
}
}
}
Time complexity : O(n∗k)
Space complexity : O(1). No extra space is used.
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]; //新数组的下标和旧下标有那么一个关系
}
for (int i = 0; i < nums.length; i++) {
nums[i] = a[i];
}
}
}
Time complexity : O(n).
Space complexity : O(n). :Another array of the same size is used.
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);
}
}
}
Time complexity : O(n).Only one pass is used.
Space complexity : O(1). Constant extra space is used.
public class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
Time complexity : O(n).n elements are reversed a total of three times.
Space complexity : O(1). No extra space is used.