585. maximum number in mountain sequence

explanation

和前面的一个元素比

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

* @param nums: a mountain sequence which increase firstly and then decrease
* @return: then mountain top
*/
public int mountainSequence(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
}

int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] > nums[mid - 1]) { // target on the right(include mid)
start = mid;
} else if (nums[mid] < nums[mid - 1]) { // target on the left(exclude mid)
end = mid - 1;
} else {
end = mid;//start = mid; 不会出现这种情况,in this case, can't do binary search
}
}
if (nums[start] > nums[end]) {
return nums[start];
} else {
return nums[end];
}

}
}

complexity

time: O(log(n))
space: O(1)