Skip to content

Commit 152d4b2

Browse files
committed
add solution of problem 154: find minimum in rotated sorted array II
1 parent 201f1af commit 152d4b2

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
> Follow up for "Find Minimum in Rotated Sorted Array":
2+
> What if duplicates are allowed?
3+
>
4+
> Would this affect the run-time complexity? How and why?
5+
>
6+
7+
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
8+
9+
(i.e., `0 1 2 4 5 6 7` might become `4 5 6 7 0 1 2`).
10+
11+
Find the minimum element.
12+
13+
The array may contain duplicates.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
public class Solution {
2+
public int findMin(int[] nums) {
3+
if (nums == null || nums.length == 0)
4+
return Integer.MIN_VALUE;
5+
6+
int numsLen = nums.length;
7+
int left = 0;
8+
int right = numsLen - 1;
9+
10+
if (nums[left] == nums[right]) {
11+
int minValue = nums[0];
12+
for (int i = 1; i < numsLen; i++) {
13+
if (nums[i] < minValue)
14+
minValue = nums[i];
15+
}
16+
17+
return minValue;
18+
} else if (nums[left] < nums[right]) {
19+
return nums[left];
20+
} else {
21+
while (left + 1 < right) {
22+
int mid = (left + right) >> 1;
23+
if (nums[mid] >= nums[left]) {
24+
left = mid;
25+
} else {
26+
right = mid;
27+
}
28+
}
29+
30+
return nums[right];
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)