- 案例分析
- 遍历
class Solution { public int findPeakElement(int[] nums) { //nums[-1] nums[n] 是无穷 也就是说需要看nums[0] nums[n-1] int n = nums.length; if(n==0||n==1)return 0; if(nums[0]>nums[1])return 0; if(nums[n-1]>nums[n-2])return n-1; for(int i = 1 ; i < n-1 ; i++) { if(nums[i]>nums[i-1]&&nums[i]>nums[i+1]) return i; } return 0; } }
- 代码-二分 找到任意区域最大值即可
class Solution { public int findPeakElement(int[] nums) { //nums[-1] nums[n] 是无穷 也就是说需要看nums[0] nums[n-1] int n = nums.length; if(n==0)return 0; int l = 0; int r = n-1; while(l<r) { int mid = (l + r)/2; if (nums[mid] > nums[mid + 1]) r = mid; else l = mid + 1; } return l; } }