A peak element is an element that is greater than its neighbors.
Given an input array wherenum[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 thatnum[-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.
這道題沒啥可說的。用loop來循環比較就可以了。
只是需要注意,題目中說了不考慮第一個數為peak element,但是對于最后一個數,只要這個數大于了前面的那個數,它就可以算作是peak element。
代碼如下。~
public class Solution { public int findPeakElement(int[] nums) { if(nums.length==1&&nums==null){ return 0; } for(int i=1;i<nums.length;i++){ if((i!=nums.length-1)&&(nums[i]>nums[i+1])&&(nums[i]>nums[i-1])){ return i; } if((i==nums.length-1)&&(nums[i]>nums[i-1])){ return i; } } return 0; }}新聞熱點
疑難解答