题解 | #找出特定体重的牛群#
找出特定体重的牛群
https://www.nowcoder.com/practice/bbc4c61a5bb64f329663b300a634ae6a
知识点:
二分查找
分析:
一般二分应用于无非下面这四种情况:
1:找大于等于数的第一个位置 (满足某个条件的第一个数)
2:找小于等于数的最后一个数 (满足某个条件的最后一个数)
3.查找最大值 (满足该边界的右边界)、
4.查找最小值 (满足该边界的左边界)
完整代码(C++) ACcode
vector<int> searchRange(vector<int>& weights, int target) { if(weights.size()==0)return {-1,-1}; int l = 0; int r = weights.size() - 1; int r1 = 0; while(l < r){ int mid = (l + r) / 2; if(weights[mid] <= target) r = mid; else l = mid + 1; } r1 = l; if(weights[l] != target) return { -1, -1 }; r = weights.size() - 1; l = 0; while(l < r){ int mid = (l + r + 1) / 2; if(weights[mid] >= target) l = mid; else r = mid - 1; } int r2 = l; return {r1,r2}; }