162. 寻找峰值
小于 1 分钟
162. 寻找峰值中等
解题思路:
遍历数组,寻找两边小,中间大的数的索引
class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1) return 0;
if(nums[0] > nums[1]) return 0;
if(nums[nums.length - 1] > nums[nums.length - 2]) return nums.length - 1;
for (int i = 1; i < nums.length - 1; i++) {
if(nums[i - 1] < nums[i] && nums[i + 1] < nums[i]){
return i;
}
}
return -1;
}
}
function findPeakElement(nums: number[]): number {
if (nums.length == 1) return 0;
if(nums[0] > nums[1]) return 0;
if(nums[nums.length - 1] > nums[nums.length - 2]) return nums.length - 1;
for (let i:number = 1; i < nums.length - 1; i++) {
if(nums[i - 1] < nums[i] && nums[i + 1] < nums[i]){
return i;
}
}
return -1;
};
Powered by Waline v2.15.5