159. find minimum in rotated sorted array

explanation

没有duplicate

  1. 不能和nums[0]比
    如果nums[mid] < nums[0], 最小在mid左边(include)
    ?如果nums[mid] > nums[0], 最小在mid右边或者左边(无法判断)

  2. 要和nums[length-1]比
    nums[mid] != nums[length - 1]
    if nums[mid] < nums[length -1], target on the left of mid
    if nums[mid] > nums[length - 1], target on the right of mid

code

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
public class  {

* @param nums: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] nums) {
// write your code here

Q: Does duplicate exist in the array?
A: assume no duplicate exists.
*/

1. 不能和nums【0】比
如果nums[mid] < nums[0], 最小在mid左边(include)
?如果nums[mid] > nums[0], 最小在mid右边或者左边(无法判断)

2. 要和nums【length-1】比
nums[mid] != nums[length - 1]
if nums[mid] < nums[length -1], target on the left of mid
if nums[mid] > nums[length - 1], target on the right of mid
*/

if (nums == null || nums.length == 0) {
return -1;
}

int start = 0, end = nums.length - 1;
int target = nums[nums.length - 1];
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] < target) {
end = mid;
} else if (nums[mid] > target) {
start = mid;
}
}
if (nums[start] <= nums[end]) {
return nums[start];
} else {
return nums[end];
}


}
}