题解 | #找出特定体重的牛群#
找出特定体重的牛群
https://www.nowcoder.com/practice/bbc4c61a5bb64f329663b300a634ae6a
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weights int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] searchRange (int[] weights, int target) { int left = fingLeftBoundry(weights, target); int right = findRightBoundry(weights, target); if (left <= right) { return new int[] {left, right}; } else { return new int[] {-1, -1}; } // write code here } private int fingLeftBoundry(int[] weights, int target) { int left = 0, right = weights.length - 1; int leftBoundry = -1; while (left <= right) { int mid = left + (right - left) / 2; if (weights[mid] == target) { leftBoundry = mid; right = mid - 1; } else if (weights[mid] < target) { right = mid - 1; } else { left = mid + 1; } } return leftBoundry; } private int findRightBoundry(int[] weights,int target){ int left=0,right=weights.length-1; int rightBoundry =-1; while(left<=right){ int mid = left + (right-left)/2; if(weights[mid]==target){ rightBoundry = mid; left = mid+1; }else if(weights[mid]<target){ right = mid-1; }else{ left = mid+1; } } return rightBoundry; } }
首先使用两次二分查找分别找到特定体重牛的左边界和右边界,然后根据找到的左边界和右边界返回结果。左边界的查找函数 findLeftBoundary
找到第一个等于目标体重的位置,右边界的查找函数 findRightBoundary
找到最后一个等于目标体重的位置。如果左边界小于等于右边界,说明存在特定体重的牛,返回起始位置和结束位置,否则返回 [-1, -1] 表示没有找到。