题解 | #找出特定体重的牛群#
找出特定体重的牛群
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) { // write code here int leftIndex = findLeftIndex(weights, target); if (leftIndex == -1) { return new int[] {-1, -1}; } int rightIndex = findRightIndex(weights, target); return new int[] {leftIndex, rightIndex}; } private int findLeftIndex(int[] weights, int target) { int left = 0, right = weights.length - 1; int index = -1; while (left <= right) { int mid = left + (right - left) / 2; if (weights[mid] == target) { index = mid; right = mid - 1; } else if (weights[mid] < target) { right = mid - 1; } else { left = mid + 1; } } return index; } private int findRightIndex(int[] weights, int target) { int left = 0, right = weights.length - 1; int index = -1; while (left <= right) { int mid = left + (right - left) / 2; if (weights[mid] == target) { index = mid; left = mid + 1; } else if (weights[mid] < target) { right = mid - 1; } else { left = mid + 1; } } return index; } }
考察的知识点:
- 二分查找:利用二分查找的思想在有序数组中寻找目标元素的起始和结束位置。
- 数组操作:根据比较结果更新查找范围。