-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-154-Find-Minimum-in-Rotated-Sorted-Array-II.java
76 lines (66 loc) · 2.72 KB
/
LeetCode-154-Find-Minimum-in-Rotated-Sorted-Array-II.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Analysis:
"154. Find Minimum in Rotated Sorted Array II" is similar to "153. Find Minimum in Rotated Sorted Array".
We can still compare nums[mid] with nums[hi]. The only difference to 153 is the case of nums[mid]==nums[hi], we cannot judge.
nums[mid] > nums[hi] -> search nums[mid+1, hi]
nums[mid] < nums[hi] -> search nums[lo, mid]
nums[mid] == nums[hi], we cannot judge in which side.
[3, 1, 3, 3, 3, 3]
[3, 3, 3, 1, 2, 3]
So in this case, we can only ensure that nums[hi] is not minmum, so we just do hi--
*/
public class Solution {
// 1.
// public int findMin(int[] nums) {
// if(nums == null || nums.length == 0) return -1;
// if(nums.length == 1) return nums[0];
// int lo = 0, hi = nums.length - 1;
// while(lo < hi){
// int mid = lo + (hi - lo) / 2;
// if(nums[mid] > nums[hi]){
// lo = mid + 1;
// }else if(nums[mid] < nums[hi]){
// hi = mid;
// }else{
// hi--;
// }
// }
// return nums[lo];
// }
// 2.
public int findMin(int[] nums) {
if(nums == null || nums.length == 0) return -1;
if(nums.length == 1) return nums[0];
int lo = 0, hi = nums.length - 1;
while (lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > nums[hi]) {
lo = mid + 1; // the only case is mid is in the left of the pivot
} else if (nums[mid] < nums[hi]) {
hi = mid; // we are not sure if mid is the smallest or not, what we are sure is smallest is not in (mid, hi]
} else {
// we are not sure if mid is the smallest or not, but we are sure that hi is not smallest.
hi--;
}
}
return Math.min(nums[lo], nums[hi]);
}
// wrong answer
// public int findMin(int[] nums) {
// if(nums == null || nums.length == 0) return -1;
// if(nums.length == 1) return nums[0];
// int lo = 0, hi = nums.length - 1;
// while (lo + 1 < hi) {
// int mid = lo + (hi - lo) / 2;
// if (nums[mid] < nums[lo]) {
// hi = mid; // the only case is mid is in the right of pivot, and we are not sure if mid is the smallest or not
// } else if (nums[mid] > nums[lo]) {
// lo = mid; // we are not sure if mid is the smallest or not
// } else {
// // we are not sure if mid is the smallest or not, but we are sure that hi is not smallest.
// lo++;
// }
// }
// return Math.min(nums[lo], nums[hi]);
// }
}