Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

189. Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

1
2
3
4
5
6
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

1
2
3
4
5
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

三次反轉。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
TC: O(n), SC: O(1)

public class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length; // [1,2,3,4,5,6,7]
reverse(nums, 0, nums.length - 1); // [7,6,5,4,3,2,1]
reverse(nums, 0, k - 1); //[5,6,7,4,3,2,1]
reverse(nums, k, nums.length - 1); // [5,6,7,1,2,3,4]
}

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--;
}
}
}

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels