1. 程式人生 > >lintcode585- Maximum Number in Mountain Sequence- medium

lintcode585- Maximum Number in Mountain Sequence- medium

com ins blog alt on() strong exceptio public class

Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top.

Example

Given nums = [1, 2, 4, 8, 6, 3] return 8
Given nums = [10, 9, 8, 7], return 10

用OOXX的二分法(find the first X)。特征O:nums[mid+1]-nums[mid]>0; 特征X:nums[mid+1]-nums[mid]<0。 1.中間用nums[mid+1]的時候可以直接用,因為這種while條件寫法+mid總偏左本來就決定了mid最遠到倒數第二個數。 技術分享
public class Solution {
    /*
     * @param nums: a mountain sequence which increase firstly and then decrease
     * @return: then mountain top
     */
    public int mountainSequence(int[] nums) {

        // 要怎麽處理輸入???
        if (nums == null || nums.length == 0){
            throw new IllegalArgumentException();
        }

        
int start = 0; int end = nums.length - 1; while (start + 1 < end){ int mid = start + (end - start) / 2; // 應該不用判斷mid < nums.length - 1把,天然的。 // 等於情況似乎無法處理,輸入應該這種描述不會給吧 if (nums[mid + 1] - nums[mid] > 0){ start = mid; }
else { end = mid; } } if (nums[start] > nums[end]){ return nums[start]; } return nums[end]; } }

lintcode585- Maximum Number in Mountain Sequence- medium