题解 | #找出特定体重的牛群#
找出特定体重的牛群
https://www.nowcoder.com/practice/bbc4c61a5bb64f329663b300a634ae6a
考察二分查找。需要对于边界进行把握,寻找左边界时如果中间值更大就向右移动,反之就将其更新到中间处。寻找右边界时候,如果中间值小于target,就将右边界向左移动到mid-1,反之将左边界移动到mid
完整Java代码如下
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weights int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] searchRange (int[] weights, int target) { // write code here int start = 0; int end = weights.length - 1; while (start <= end) { int mid = (start + end) / 2; if (weights[mid] < target) { end = mid - 1; } else if (weights[mid] > target) { start = mid + 1; } else { start = mid; end = mid; while (start >= 0 && weights[start] == target) { start--; } while (end < weights.length && weights[end] == target) { end++; } return new int[] {start + 1, end - 1}; } } return new int[] {-1, -1}; } }