LeetCode162-寻找峰值 二分找索引,对于mid,如果处于上坡,则答案在右边,如果处于下坡,答案在左边,如果处于低谷,答案任意,如果处于峰顶,即为答案。 注意特判0和nums.szie()-1两个位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int findPeakElement(vector<int>& nums) { int l = 0, r = nums.size()-1, mid; int res; while(l <= r) { mid = (l + r) / 2;
if((mid == 0 || nums[mid] > nums[mid - 1]) && (mid == nums.size() - 1 || nums[mid] > nums[mid + 1])) { res = mid; break; } else if((mid == 0 || nums[mid-1] < nums[mid]) && (mid < nums.size() - 1 && nums[mid] < nums[mid+1])) l = mid + 1; else if((mid > 0 && nums[mid-1] > nums[mid]) && (mid == nums.size() - 1 || nums[mid] > nums[mid+1])) r = mid - 1; else l = mid + 1; } return res; } };
|