https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
给定一个有序数组,可能包含有重复元素,问target在数组中的起始位置和结束位置,要求复杂度 \(O(logN)\)
------------------------------------------------------------------
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 5
Output: [0,0]
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int lo = 0, hi = nums.size()-1; if (hi==-1) { vector<int> result={-1,-1}; return result; } while(lo < hi && nums[lo] != nums[hi]) // nums[lo]==nums[hi]时,从lo 到hi都是相同的数字,因此可以直接退出 { int mi = (lo + hi)>>1; if(nums[mi]<target) lo = mi + 1; else if(target < nums[mi]) hi = mi -1; else // 如果 target和nums[mi]相等,则 lo+1或者hi-1 进行选择 if(target==nums[lo])// 如果target和nums[lo]相等,lo不动,动hi --hi; else // 如果target 和nums[lo]不相等,则动lo,hi不动 ++lo; } vector<int> result; if(nums[lo]!=target) lo = -1,hi = -1; result.push_back(lo); result.push_back(hi); return result; } };
结果:
Runtime: 8 ms, faster than 84.44% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
来源:https://www.cnblogs.com/qiulinzhang/p/12530748.html