题解 | #找出特定体重的牛群#
找出特定体重的牛群
https://www.nowcoder.com/practice/bbc4c61a5bb64f329663b300a634ae6a
知识点
二分
解题思路
先通过二分法找到与目标target相等值的下标,在再这个下标的基础上找到目标值左边与右边的边界下标。
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 n = weights.length; int left = 0, right = n - 1; while(left <= right){ int mid = left + (right - left) / 2; if(weights[mid] > target){ left = mid + 1; } else if(weights[mid] < target) { right = mid - 1; } else { int start = mid, end = mid; while(start > 0 && weights[start - 1] == weights[start]) start--; while(end < n - 1 && weights[end] == weights[end + 1]) end++; return new int[]{start,end}; } } return new int[]{-1,-1}; } }