Skip to content

Commit 2fe08c3

Browse files
add a solution for 189
1 parent 1efa219 commit 2fe08c3

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

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

+24
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,28 @@ private void reverse(int[] nums, int start, int end) {
6161
}
6262
}
6363
}
64+
65+
public static class Solution4 {
66+
/**
67+
* O(n) time
68+
* O(1) space
69+
* The most optimal, we can safely ignore all the above three solutions... :)
70+
*/
71+
public void rotate(int[] nums, int k) {
72+
k = k % nums.length;
73+
int count = 0;
74+
for (int start = 0; count < nums.length; start++) {
75+
int current = start;
76+
int prev = nums[start];
77+
do {
78+
int nextIndex = (current + k) % nums.length;
79+
int tmp = nums[nextIndex];
80+
nums[nextIndex] = prev;
81+
prev = tmp;
82+
current = nextIndex;
83+
count++;
84+
} while (start != current);
85+
}
86+
}
87+
}
6488
}
+21-4
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,59 @@
11
package com.fishercoder;
22

3-
import com.fishercoder.common.utils.CommonUtils;
43
import com.fishercoder.solutions._189;
54
import org.junit.BeforeClass;
65
import org.junit.Test;
76

7+
import static org.junit.Assert.assertArrayEquals;
8+
89
public class _189Test {
910
private static _189.Solution1 solution1;
1011
private static _189.Solution2 solution2;
1112
private static _189.Solution3 solution3;
13+
private static _189.Solution4 solution4;
1214
private static int[] nums;
1315

1416
@BeforeClass
1517
public static void setup() {
1618
solution1 = new _189.Solution1();
1719
solution2 = new _189.Solution2();
1820
solution3 = new _189.Solution3();
21+
solution4 = new _189.Solution4();
1922
}
2023

2124
@Test
2225
public void test1() {
2326
nums = new int[]{1, 2, 3};
2427
solution1.rotate(nums, 1);
25-
CommonUtils.printArray(nums);
28+
assertArrayEquals(new int[]{3, 1, 2}, nums);
2629
}
2730

2831
@Test
2932
public void test2() {
3033
nums = new int[]{1, 2, 3};
3134
solution2.rotate(nums, 1);
32-
CommonUtils.printArray(nums);
35+
assertArrayEquals(new int[]{3, 1, 2}, nums);
3336
}
3437

3538
@Test
3639
public void test3() {
3740
nums = new int[]{1, 2, 3};
3841
solution3.rotate(nums, 1);
39-
CommonUtils.printArray(nums);
42+
assertArrayEquals(new int[]{3, 1, 2}, nums);
43+
}
44+
45+
@Test
46+
public void test4() {
47+
nums = new int[]{1, 2, 3};
48+
solution4.rotate(nums, 1);
49+
assertArrayEquals(new int[]{3, 1, 2}, nums);
50+
}
51+
52+
@Test
53+
public void test5() {
54+
nums = new int[]{-1, -100, 3, 99};
55+
solution4.rotate(nums, 2);
56+
assertArrayEquals(new int[]{3, 99, -1, -100}, nums);
4057
}
4158

4259
}

0 commit comments

Comments
 (0)