一刷 06/2022
Version #1 Using Cyclic Replacements
Time O(N)
Space O(1)
class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
if (k % len == 0) {
return;
}
int cnt = 0;
int startIndex = 0;
while (cnt < len) {
int index = startIndex;
int prev = nums[index];
do {
index = (index + k) % len;
int curr = nums[index];
nums[index] = prev;
cnt++;
prev = curr;
} while (index != startIndex);
startIndex++;
}
}
}
Version #2 Reversion
Time O(N)
Space O(1)
class Solution {
public void rotate(int[] nums, int k) {
if (k % nums.length == 0) {
return;
}
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
No comments:
Post a Comment