162. Find Peak Element
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.
分析:一般解法:
由于最左边最小值是-∞,所以最先的时候,array是单调递增的。只要我们找到第一个 nums[i] > nums[i + 1] ,那么就把答案找到了。
public class Solution { public int findPeakElement(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) return i; } return nums.length - 1; } }
O(lgN)解法
1 class Solution { 2 public int findPeakElement(int[] nums) { 3 int l = 0, r = nums.length - 1; 4 while (l < r) { 5 int mid = (l + r) / 2; 6 if (nums[mid] > nums[mid + 1]) 7 r = mid; 8 // if all the left numbers are smaller than nums[mid], then nums[mid] is the result 9 // if there exists one number which is greater than nums[mid], we can also find another number as result 10 // Therefore, we can break it into halves 11 else 12 l = mid + 1; 13 } 14 return l; 15 } 16 }
                    
                
                
            
        
浙公网安备 33010602011771号