162. 寻找峰值
https://leetcode.cn/problems/find-peak-element/description/思路
https://leetcode.cn/problems/find-peak-element/solutions/998152/xun-zhao-feng-zhi-by-leetcode-solution-96sj/Code
二分查找法。需要对 两个端点做特殊处理。
class Solution { public: int findPeakElement(vector<int>& nums) { int n = nums.size(); if (n == 1){ return 0; } int left = 0; int right = n-1; int ans = -1; while(left<=right){ int middle = (left+right) / 2; if (middle == 0){ if (nums[middle] < nums[middle+1]){ ans = middle+1; } else { ans = middle; } break; } else if (middle == n-1){ if (nums[middle] > nums[middle-1]){ ans = middle; } else { ans = middle-1; } break; } if (nums[middle] > nums[middle+1] && nums[middle] > nums[middle-1]){ ans = middle; break; } if (nums[middle] < nums[middle+1]){ left = middle+1; }else{ right = middle-1; } } return ans; } };
标签:nums,int,寻找,峰值,middle,ans,leetcode,162 From: https://www.cnblogs.com/lightsong/p/18063545