LeetCode C++ 34. Find First and Last Position of Element in Sorted Array【Binary Search】中等

tech2022-08-25  122

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n) .

If the target is not found in the array, return [-1, -1] .

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]

Constraints:

0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9nums is a non decreasing array.-10^9 <= target <= 10^9

题意:在排序数组中确定数字 target 出现的左右边界。


解法1 STL

用STL的二分查找函数。代码如下:

class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int left = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); int right = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1; if (left > right) return {-1, -1}; return vector<int>{left, right}; } };

解法2 手写二分上下界函数

class Solution { private: //找到第一个>=v的元素的位置 int lowerBound(vector<int>& A, int x, int y, int v) { while (x < y) { int m = x + (y - x) / 2; if (A[m] >= v) y = m; else x = m + 1; } return x; } //找到第一个>v的元素的位置 int upperBound(vector<int>& A, int x, int y, int v) { while (x < y) { int m = x + (y - x) / 2; if (A[m] > v) y = m; else x = m + 1; } return x; } public: vector<int> searchRange(vector<int>& nums, int target) { if (nums.empty()) return {-1, -1}; //特判空 int n = nums.size(); int first = lowerBound(nums, 0, n, target); //第一个<= if (first >= n || nums[first] != target) return vector<int>{-1, -1}; //特判不存在 int last = upperBound(nums, 0, n, target); //第一个< return vector<int>{first, last - 1}; } };

运行效率如下:

执行用时:20 ms, 在所有 C++ 提交中击败了74.62% 的用户 内存消耗:13.5 MB, 在所有 C++ 提交中击败了67.57% 的用户
最新回复(0)