Maximum Number in Mountain Sequence
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
int l = 0, r = nums.length - 1;
int mid = (l + r) / 2;
int lst = -1;
while(l < r){
if(nums[mid] < nums[mid + 1])
l = mid;
else r = mid;
mid = (l + r) / 2;
if(mid == lst){
break;
}
lst = mid;
}
if(nums[l] > nums[r]){
return nums[l];
}
else{
return nums[r];
}
}
}
class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountainSequence(self, nums):
# write your code here
left, right = 0, len(nums)-1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] < nums[mid+1]:
left = mid
else:
right = mid
if nums[right] > nums[left]:
return nums[right]
else:
return nums[left]
最后更新于
这有帮助吗?