[LeetCode] 34. Search for a Range
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 34. Search for a Range
[LeetCode]34. Search for a Range
LeetCode OJ 34Search for a Range
[leetcode-34-Search for a Range]