Maximum Number in Mountain Sequence
O(logN)
Important Point:
if there "mid" exists, it has at laest three elements in "nums", because otherwise it will not come inside the loop. So later, we don't have to check whether "mid -1" and "mid + 1" are OutOfBond.
public class Solution { /** * @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 -1; } int start = 0; int end = nums.length - 1; while(start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) { return nums[mid]; } else if (nums[mid] > nums[mid - 1] && nums[mid] < nums[mid + 1]) { start = mid; } else { end = mid; } } if (nums[start] >= nums[end]) { return nums[start]; } if (nums[end] > nums[start]) { return nums[end]; } return -1; } }
posted on 2017-05-04 05:28 codingEskimo 阅读(93) 评论(0) 编辑 收藏 举报