-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Minimum in Rotated Sorted Array II.java
53 lines (45 loc) · 1.69 KB
/
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
/*
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
time = O(n) if they are all the same
space = O(1)
*/
class Solution {
public int findMin(int[] nums) {
// 这道题目在面试中不会让写完整的程序
// 只需要知道最坏情况下 [1,1,1....,1] 里有一个0
// 这种情况使得时间复杂度必须是 O(n)
// 因此写一个for循环就好了 find the min value
// 如果你觉得,不是每个情况都是最坏情况,你想用二分法解决不是最坏情况的情况,那你就写一个二分吧。
// 反正面试考的不是你在这个题上会不会用二分法。这个题的考点是你想不想得到最坏情况。
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
// right part
if (nums[mid] < nums[end]) {
end = mid;
// left part
} else if (nums[mid] > nums[end]) {
start = mid;
// nums[mid] == nums[end], we need to de-duplilcation
} else {
end--;
}
}
return nums[start] <= nums[end] ? nums[start] : nums[end];
}
}