classSolution { public: intsearchInsert(vector<int>& nums, int target){ int left{}, right = nums.size() - 1; int mid{}; while(left <= right) { mid = (left + right) / 2; if(nums[mid] < target) left = mid + 1; elseif (nums[mid] > target) right = mid - 1; else return mid; } return right + 1; } };
stl库解法:使用lower_bound函数。
classSolution { public: intsearchInsert(vector<int>& nums, int target){ auto beginIter = nums.begin(); return std::distance(beginIter, lower_bound(beginIter, nums.end(), target)); } };
34.在排序数组中查找元素的第一个和最后一个位置
思路:使用二分查找获取左边界和右边界。
如果左边界和有边界的值相差小于2,则不存在。
否则返回左边界+1和有边界-1。
核心代码:对二分中的target==nums[mid]进行合并。
如果合并到left+1,则最终会逼近右边界。
如果合并到right+1,则最终会逼近左边界。
classSolution { private: intsearchLowIndex(vector<int>& nums, int target) { int left{}, right = nums.size() - 1; int mid{}; int leftBord = -2; //test if in range while(left <= right) { mid = left + (right - left) / 2; if(nums[mid] < target) left = mid + 1; else leftBord = right = mid - 1; } return leftBord; }
intsearchHighIndex(vector<int>& nums, int target) { int left{}, right = nums.size() - 1; int mid{}; int rightBord = -2; //test if in range while(left <= right) { mid = left + (right - left) / 2; if(nums[mid] > target) right = mid - 1; else rightBord = left = mid + 1; } return rightBord; } public: vector<int> searchRange(vector<int>& nums, int target){ int leftIndex = searchLowIndex(nums, target); int rightIndex = searchHighIndex(nums, target); if(leftIndex == -2 || rightIndex == -2) //out of range return {-1, -1}; elseif(rightIndex - leftIndex >= 2) //in range and find left and right return {leftIndex + 1, rightIndex - 1}; else//in range but not find return {-1, -1}; } };