标签:range 左右 code ret color while target 相关 span
方法:使用逼近的方法,先寻找左边边界,再找右边界,这与二分查找中边界的更新顺序相关
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> result = {-1, -1}; int ll=0, lr=nums.size()-1; while(ll <= lr) { int mid = (ll+lr)/2; if(nums[mid] < target) ll = mid + 1; else lr = mid - 1; } int rl = 0, rr = nums.size()-1; while(rl <= rr) { int mid = (rl + rr) / 2; if(nums[mid] > target) rr = mid - 1; else rl = mid + 1; } if(ll <= rr) { result[0] = ll; result[1] = rr; } return result; } };
或者直接找到一个值后左右逼近即可。
标签:range 左右 code ret color while target 相关 span
原文地址:http://www.cnblogs.com/chengyuz/p/6816352.html