考察知识点:二分
题目分析:
通过二分的方式找到左右边界。
当我们寻找左边界时,如果发现mid所指数大于target,就将l移动到mid + 1,如果mid小于等于target,说明mid在left右边,将r移动到mid。
当我们寻找右边界时,如果发现mid所指数小于target,就将r移动到mid - 1,如果mid所指数大于等于target,说明mid在right左边,将l移动到mid。
所用编程语言:C++
#include <cstdio> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weights int整型vector * @param target int整型 * @return int整型vector */ vector<int> searchRange(vector<int>& weights, int target) { // write code here int size = weights.size(); if (size == 0) return {-1, -1}; int l = 0, r = size - 1; int left, right; while (l < r) { int mid = l + r >> 1; if (weights[mid] <= target) r = mid; else l = mid + 1; } left = weights[l] == target ? l : -1; l = 0, r = size - 1; while (l < r) { int mid = l + r + 1 >> 1; if (weights[mid] >= target) l = mid; else r = mid - 1; } right = weights[l] == target ? l : -1; return {left, right}; } };