前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
Note:
这个题目简单一点就是遍历一遍。应该可以用类二分查找的方式解决
Your runtime beats 3.07% of java submissions.
Your solution should be in logarithmic complexity.
public class Solution {
public int findPeakElement(int[] nums) {
if(nums.length == 1)return 0;
for(int i = 0; i < nums.length; i ++){
if(i == 0){ if(nums[i] > nums[i+1]) return i;}
else if( i == nums.length - 1) { if(nums[i] > nums[i-1]) return i;}
else {if(nums[i] > nums[i-1] && nums[i] > nums[i+1]) return i;}
}
return 0;
}
}