Skip to content

Commit 3b57957

Browse files
refactor 189
1 parent 64d8565 commit 3b57957

File tree

2 files changed

+42
-11
lines changed

2 files changed

+42
-11
lines changed

src/main/java/com/fishercoder/solutions/_189.java

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,28 @@
2323
Note:
2424
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
2525
Could you do it in-place with O(1) extra space?
26-
2726
* */
2827

2928
public class _189 {
3029

3130
public static class Solution1 {
31+
/**
32+
* O(n*k) time
33+
* O(1) space
34+
*/
35+
public void rotate(int[] nums, int k) {
36+
int tmp;
37+
for (int i = 0; i < k; i++) {
38+
tmp = nums[nums.length - 1];
39+
for (int j = nums.length - 1; j > 0; j--) {
40+
nums[j] = nums[j - 1];
41+
}
42+
nums[0] = tmp;
43+
}
44+
}
45+
}
46+
47+
public static class Solution2 {
3248
/**
3349
* using an extra array of the same size to copy it
3450
* O(n) time
@@ -46,19 +62,27 @@ public void rotate(int[] nums, int k) {
4662
}
4763
}
4864

49-
public static class Solution2 {
65+
public static class Solution3 {
5066
/**
67+
* reverse three times
5168
* O(n) time
5269
* O(1) space
5370
*/
5471
public void rotate(int[] nums, int k) {
55-
int tmp;
56-
for (int i = 0; i < k; i++) {
57-
tmp = nums[nums.length - 1];
58-
for (int j = nums.length - 1; j > 0; j--) {
59-
nums[j] = nums[j - 1];
60-
}
61-
nums[0] = tmp;
72+
int len = nums.length;
73+
k %= len;
74+
reverse(nums, 0, len - 1);
75+
reverse(nums, 0, k - 1);
76+
reverse(nums, k, len - 1);
77+
}
78+
79+
private void reverse(int[] nums, int start, int end) {
80+
while (start < end) {
81+
int tmp = nums[start];
82+
nums[start] = nums[end];
83+
nums[end] = tmp;
84+
start++;
85+
end--;
6286
}
6387
}
6488
}

src/test/java/com/fishercoder/_189Test.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,28 +8,35 @@
88
public class _189Test {
99
private static _189.Solution1 solution1;
1010
private static _189.Solution2 solution2;
11+
private static _189.Solution3 solution3;
1112
private static int[] nums;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _189.Solution1();
1617
solution2 = new _189.Solution2();
18+
solution3 = new _189.Solution3();
1719
}
1820

1921
@Test
2022
public void test1() {
2123
nums = new int[]{1, 2, 3};
22-
2324
solution1.rotate(nums, 1);
2425
CommonUtils.printArray(nums);
2526
}
2627

2728
@Test
2829
public void test2() {
2930
nums = new int[]{1, 2, 3};
30-
3131
solution2.rotate(nums, 1);
3232
CommonUtils.printArray(nums);
3333
}
3434

35+
@Test
36+
public void test3() {
37+
nums = new int[]{1, 2, 3};
38+
solution3.rotate(nums, 1);
39+
CommonUtils.printArray(nums);
40+
}
41+
3542
}

0 commit comments

Comments
 (0)