vector<int> searchRange(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; int mid; int position = -1; while (left <= right) { mid = (left + right) / 2; if (nums[mid] == target) { position = mid; break; } elseif (nums[mid] < target)left = mid + 1; else right = mid - 1; } if (position == -1)return{ -1,-1 }; int begin = position, end = position; while (begin > 0 && nums[begin-1] == target)begin--; while (end<nums.size()-1 && nums[end+1] == target)end++; return{ begin,end }; }
原来是有库函数的啊!
lower_bound(): 指向首个不小于 value 的元素的迭代器,或若找不到这种元素则为 last upper_bound(): 指向首个大于 value 的元素的迭代器,或若找不到这种元素则为 last
intsearchInsert(vector<int>& nums, int target){ auto left = lower_bound(nums.begin(), nums.end(), target); int res = left - nums.begin(); return res; }