赞
踩
int PeakIndexInMountainArray(vector<int>& arr) { int left = 1, right = arr.size() - 2; while(left < right) { int mid = left + (right - left + 1) / 2; if(arr[mid] >= arr[mid - 1]) { left = mid; } else { right = mid - 1; } } return left; }
本题虽然在数据上,是明显的无序,但是仍然可以找到二段性的存在,可以使用二分查找
任取⼀个点mid
,与下⼀个点mid + 1
,会有如下两种情况:
arr[mid] > arr[mid + 1]
arr[mid] < arr[mid + 1]
int FindPeakElement(vector<int>& nums) { int left = 0, right = nums.size() - 1; while(left < right) { int mid = left + (right - left) / 2; if(nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; } } return left; }
[A,B]
区间内的点都严格> D
点的值,C
点的值严格< D
点的值
[C,D]
区间只有⼀个元素的时候, C
点的值可能= D
点的值int findMin(vector<int>& nums) { int n = nums.size(); int left = 0, right = n - 1; while(left < right) { int mid = left + (right - left) / 2; if(nums[mid] > nums[n - 1]) { left = mid + 1; } else { right = mid; } } return nums[left]; }
int takeAttendance(vector<int>& records) { int left = 0, right = records.size() - 1; while(left < right) { int mid = left + (right - left) / 2; if(mid == records[mid]) { left = mid + 1; } else { right = mid; } } return left == records[left] ? (left + 1) : left; // 处理边界情况 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。