-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathFind Minimum in Rotated Sorted Array II.java
More file actions
69 lines (58 loc) · 2.14 KB
/
Find Minimum in Rotated Sorted Array II.java
File metadata and controls
69 lines (58 loc) · 2.14 KB
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
/*
Medium Find Minimum in Rotated Sorted Array II My Submissions
40% Accepted
Suppose a sorted array 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
Given [4,4,5,6,7,0,1,2] return 0
Tags Expand
Binary Search Divide and Conqueri
*/
// version 1: just for loop is enough
public class Solution {
public int findMin(int[] num) {
// 这道题目在面试中不会让写完整的程序
// 只需要知道最坏情况下 [1,1,1....,1] 里有一个0
// 这种情况使得时间复杂度必须是 O(n)
// 因此写一个for循环就好了。
// 如果你觉得,不是每个情况都是最坏情况,你想用二分法解决不是最坏情况的情况,那你就写一个二分吧。
// 反正面试考的不是你在这个题上会不会用二分法。这个题的考点是你想不想得到最坏情况。
int min = num[0];
for (int i = 1; i < num.length; i++) {
if (num[i] < min)
min = num[i];
}
return min;
}
}
// version 2: use *fake* binary-search
// When num[mid] == num[hi], we couldn't sure the position of minimum in mid's left or right,
// so just let upper bound reduce one.
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == nums[end]) {
// if mid equals to end, that means it's fine to remove end
// the smallest element won't be removed
end--;
} else if (nums[mid] > nums[end]) {
start = mid + 1;
} else {
end = mid;
}
}
return nums[start];
}
}