本文主要是介绍Maximum Number in Mountain Sequence,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a mountain sequence of n
integers which increase firstly and then decrease, find the mountain top.
Example
Example 1:
Input: nums = [1, 2, 4, 8, 6, 3]
Output: 8
Example 2:
Input: nums = [10, 9, 8, 7],
Output: 10
思路: 就是两边往中间走,最后判断start和end即可,按照九章的模板写万无一失;
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 hereif(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]) {start = mid;} else { // nums[mid] > nums[mid+1];end = mid;}}if(nums[start] > nums[end]) {return nums[start];}return nums[end];}
}
这篇关于Maximum Number in Mountain Sequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!