友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
189. Rotate Array
发现官网测试用例少了一个特殊情况:如果 k
大于两倍数组长度,提交的测试就会报错,但是官网却显示通过。
数组反转的方法也不错!反转时,直接使用界限的值进行加减比较简单省事!
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input:
and k = 3 Output:[1,2,3,4,5,6,7]
[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:
Input:
[-1,-100,3,99]
and 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]
Note:
-
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
-
Could you do it in-place with O(1) extra space?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Array.
*
* Memory Usage: 37.4 MB, less than 100.00% of Java online submissions for Rotate Array.
*
* Copy from: https://leetcode.com/problems/rotate-array/solution/[Rotate Array solution - LeetCode]
*/
public void rotate(int[] nums, int k) {
if (Objects.isNull(nums) || nums.length == 0 || 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--;
}
}
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Array.
* <p>
* Memory Usage: 38 MB, less than 85.58% of Java online submissions for Rotate Array.
*/
public void rotateExtraArray(int[] nums, int k) {
if (Objects.isNull(nums) || nums.length == 0 || k % nums.length == 0) {
return;
}
k %= nums.length;
int[] temp = new int[k];
for (int i = 0; i < k; i++) {
temp[k - i - 1] = nums[nums.length - i - 1];
}
for (int i = nums.length - 1; i >= k; i--) {
nums[i] = nums[i - k];
}
for (int i = 0; i < k; i++) {
nums[i] = temp[i];
}
}