首页 > 代码库 > [LeetCode] 34. Search for a Range
[LeetCode] 34. Search for a Range
Given an array of integers 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
1 //better one from discuss, qp use l, r 2 class Solution { 3 public: 4 vector<int> searchRange(vector<int>& nums, int target) { 5 vector<int> ret(2, -1); 6 int n = nums.size(); 7 int l = 0; 8 int r = n - 1; 9 int mid; 10 11 while (l < r){ 12 mid = (l+r) /2; 13 if (target > nums[mid]) l = mid + 1; 14 else if (target <= nums[mid]) r = mid; 15 //else r = mid; // push to left 16 } 17 18 if (nums[l] != target) return ret; 19 else ret[0] = l; 20 21 r = n - 1; // no need to reinit l; 22 while (l < r){ 23 /* !!!! make the r biasd to right */ 24 mid = (l+r+1) / 2; 25 if (target < nums[mid]) r = mid - 1; 26 else if (target >= nums[mid]) l = mid; 27 //else l = mid; // move to right 28 } 29 30 ret[1] = l; 31 32 return ret; 33 } 34 };
[LeetCode] 34. Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。