标签:start 条件 情况 outline value 二分查找 return 否则 starting
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution { public : vector< int > searchRange(vector< int >& nums, int target) { return helper(nums, 0, nums.size() - 1, target); } vector< int > helper(vector< int > & nums, int l, int r, int target){ if (nums.empty()) return vector< int >{-1,-1}; if (nums[l] == target && target == nums[r]){ return vector< int >{l,r}; } else if (nums[l] <= target && target <= nums[r]){ int mid = (l + r) >> 1; vector< int > L = helper(nums, l, mid, target); vector< int > R = helper(nums, mid+1, r, target); if (L[0] != -1 && R[0] != -1){ return vector< int > {L[0],R[1]}; } else if (L[0] != -1){ return L; } else { // 剩下的 R 不为{-1, -1} 和 R 是{-1, -1}的情况可以合并 return R; } } return vector< int >{-1, -1}; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class Solution { public : vector< int > searchRange(vector< int >& nums, int target) { if (nums.empty()) return vector< int > {-1, -1}; int l = bs(nums, target); if (nums[l] == target){ int r = bs(nums, target + 1); /** * 当nums的最后一个元素是target的时候,需要将边界r自增才是可以插入target+1的位置 * 比如[2,2,2]则r的值是2,和[2,2,4]的返回值同是2, */ if (nums[r] == target) r++; return vector< int > {l, r - 1}; } else { return vector< int > {-1, -1}; } } // using binary search to find the first element in nums or the position that could be used to insert the element int bs(vector< int > & nums, int target){ int l = 0, r = nums.size() - 1, mid; while (l < r){ mid = (l + r) >> 1; if (nums[mid] < target){ l = mid + 1; } else { r = mid; } } return r; } }; |
标签:start 条件 情况 outline value 二分查找 return 否则 starting
原文地址:http://www.cnblogs.com/zhxshseu/p/c8ae187c169beb07f9646be57ee2ec22.html