Skip to content

Commit 793a36e

Browse files
refactor 154
1 parent 35b4331 commit 793a36e

File tree

2 files changed

+43
-25
lines changed

2 files changed

+43
-25
lines changed

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

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,33 @@
22

33
public class _154 {
44
public static class Solution1 {
5+
/**
6+
* My completely original solution on 10/23/2021.
7+
* Again, using a pen and paper to visualize all possible cases helps a great deal!
8+
*/
59
public int findMin(int[] nums) {
610
int left = 0;
711
int right = nums.length - 1;
8-
if (nums[left] < nums[right]) {
9-
return nums[left];
10-
}
11-
int min = nums[0];
12-
while (left + 1 < right) {
12+
while (left < right) {
13+
while (left + 1 < right && nums[left] == nums[left + 1]) {
14+
left++;
15+
}
16+
while (right - 1 > left && nums[right - 1] == nums[right]) {
17+
right--;
18+
}
1319
int mid = left + (right - left) / 2;
14-
min = Math.min(min, nums[mid]);
15-
if (nums[mid] > nums[left]) {
16-
min = Math.min(nums[left], min);
17-
left = mid + 1;
20+
if (mid == left || mid == right) {
21+
break;
22+
}
23+
if (nums[mid] < nums[right]) {
24+
right = mid;
1825
} else if (nums[mid] < nums[left]) {
19-
right = mid - 1;
20-
} else {
21-
left++;
26+
left = mid;
27+
} else if (nums[mid] > nums[right]) {
28+
left = mid + 1;
2229
}
2330
}
24-
min = Math.min(min, Math.min(nums[left], nums[right]));
25-
return min;
31+
return right >= 0 && nums[right] < nums[left] ? nums[right] : nums[left];
2632
}
2733
}
2834
}

src/test/java/com/fishercoder/_154Test.java

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,29 @@
77
import static org.junit.Assert.assertEquals;
88

99
public class _154Test {
10-
private static _154.Solution1 solution1;
11-
private static int[] nums;
10+
private static _154.Solution1 solution1;
11+
private static int[] nums;
1212

13-
@BeforeClass
14-
public static void setup() {
15-
solution1 = new _154.Solution1();
16-
}
13+
@BeforeClass
14+
public static void setup() {
15+
solution1 = new _154.Solution1();
16+
}
1717

18-
@Test
19-
public void test1() {
20-
nums = new int[] {1, 1, 1};
21-
assertEquals(1, solution1.findMin(nums));
22-
}
18+
@Test
19+
public void test1() {
20+
nums = new int[]{1, 1, 1};
21+
assertEquals(1, solution1.findMin(nums));
22+
}
23+
24+
@Test
25+
public void test2() {
26+
nums = new int[]{4, 5, 6, 7, 0, 1, 4};
27+
assertEquals(0, solution1.findMin(nums));
28+
}
29+
30+
@Test
31+
public void test3() {
32+
nums = new int[]{1, 3, 5};
33+
assertEquals(1, solution1.findMin(nums));
34+
}
2335
}

0 commit comments

Comments
 (0)