标签:lex lower end else int for search val div
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]
.
使用两次二分查找,第一次找出目标数的左边界,第二次找出目标数的右边界。最后判断边界并返回。
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { if (nums.empty()) return {-1, -1}; int lower = -1, upper = -1, mid = 0; int left = 0, right = nums.size() - 1; while (left <= right) { mid = (left + right) / 2; if (nums[mid] < target) left = mid + 1; else right = mid - 1; } lower = left; left = 0, right = nums.size() - 1; while (left <= right) { mid = (left + right) / 2; if (nums[mid] > target) right = mid - 1; else left = mid + 1; } upper = right; if (lower > upper) return {-1, -1}; else return {lower, upper}; } }; // 16 ms
标签:lex lower end else int for search val div
原文地址:http://www.cnblogs.com/immjc/p/7986213.html