Problem: 34. 在排序数组中查找元素的第一个和最后一个位置
文章目录
- 题目描述
- 思路
- 复杂度
- Code
题目描述
思路
Problem: 二分查找常用解题模板(带一道leetcode题目)
直接套用上述中的寻找左、右边界的二分查找模板即可
复杂度
时间复杂度:
O ( l o g n ) O(logn) O(logn);其中 n n n为数组nums的大小
空间复杂度:
O ( n ) O(n) O(n)
Code
class Solution {
public:/*** Finds the first and last position of an element in a sorted array** @param nums Given array* @param target Given target number* @return vector<int>*/vector<int> searchRange(vector<int>& nums, int target) {if (nums.size() == 0) {return {-1, -1};}vector<int> res(2);res[0] = left_bound(nums, target);res[1] = right_bound(nums, target);return res;}/*** Queries the left boundary for a number less than the specified number** @param nums Given array* @param target Given target number* @return int*/int left_bound(vector<int>& nums, int target) {int left = 0;int right = nums.size() - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) {right = mid - 1;} else if (nums[mid] > target) {right = mid - 1;} else if (nums[mid] < target) {left = mid + 1;}}// Check out of boundsif (left >= nums.size() || nums[left] != target) {return -1;}return left;}/*** Queries the right boundary for a number less than the specified number* * @param nums Given array* @param target Given target number* @return int*/int right_bound(vector<int>& nums, int target) {int left = 0;int right = nums.size() - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) {left = mid + 1;} else if (nums[mid] > target) {right = mid - 1;} else if (nums[mid] < target) {left = mid + 1;}}// Check out of boundsif (right < 0 || nums[right] != target) {return -1;}return right;}
};