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 inde ...
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.
代碼如下:
1 public class Solution { 2 public int findPeakElement(int[] nums) { 3 if(nums.length==1) 4 return 0; 5 if(nums.length==2&&nums[0]<nums[1]) 6 return 1; 7 8 for(int i=1;i<nums.length-1;i++) 9 { 10 if(nums[i]>nums[i-1]&&nums[i]>nums[i+1]) 11 return i; 12 } 13 if(nums[nums.length-1]>nums[nums.length-2]) 14 return nums.length-1; 15 16 return 0; 17 } 18 }