2019.8.20 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
题目时间复杂度要求是o(lgn),因此需要考虑递归或者二分迭代来做。
如果将数组分为左右两部分,考察中值mid已经mid+1的大小。若mid更大则必有峰值出现在begin-mid之间,若mid较小则必有峰值出现在mid+1~end之间。由此可以进行二分迭代。
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
峰值元素是指其值大于左右相邻值的元素。
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞。
示例 1:
输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5
解释: 你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。
说明: 你的解法应该是 O(logN) 时间复杂度的。
/**
*
* A peak element is an element that is greater than its neighbors.
* Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
* The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
* You may imagine that nums[-1] = nums[n] = -∞.
* 峰值元素是指其值大于左右相邻值的元素。
* 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
* 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
* 你可以假设 nums[-1] = nums[n] = -∞。
*
*/
public class FindPeakElement {
public int findPeakElement(int[] nums) {
int begin = 0;
int end = nums.length - 1;
while(begin < end){
int mid = (begin + end) >> 1;
if(nums[mid] > nums[mid + 1]){
end = mid;
}else{
begin = mid + 1;
}
}
return end;
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#