题解 | #找出特定体重的牛群#
找出特定体重的牛群
https://www.nowcoder.com/practice/bbc4c61a5bb64f329663b300a634ae6a?tpId=354&tqId=10594891&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weights int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] searchRange (int[] weights, int target) { int leftBorder = getLeftRange(weights, target); int rightBorder = getRightRange(weights, target); int[] result = new int[2]; if (leftBorder == -2 || rightBorder == -2) { result[0] = -1; result[1] = -1; return result; } if (rightBorder - leftBorder > 1) { result[0] = leftBorder + 1; result[1] = rightBorder - 1; return result; } result[0] = -1; result[1] = -1; return result; } public int getRightRange(int[] nums, int target) { int left = 0, right = nums.length - 1; int rightBorder = -2; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] >= target) { left = mid + 1; rightBorder = left; } else { right = mid - 1; } } return rightBorder; } public int getLeftRange(int[] nums, int target) { int left = 0, right = nums.length - 1; int leftBorder = -2; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] <= target) { right = mid - 1; leftBorder = right; } else { left = mid + 1; } } return leftBorder; } }
本题知识点分析:
1.二分查找
2.双指针
3.数组遍历和赋值
本题解题思路分析:
1.创建两个单独的功能函数用于寻找最左边界和最右边界
2.如果无法找到目标元素,返回-1,-1
3.如果rightBorder-leftBorder>1说明有连续区间,将left+1,right-1,然后进行返回
4.两个功能函数就是二分查找,无非是等号和什么时候取+1的问题,只要思考好自己找的好最左边还是最右边,是等于还是大于还是小于,这些问题就很容易做出
本题使用编程语言: Java
高频面试算法题解 文章被收录于专栏
高频面试算法题解,每天一小步,人生一大步,跟着一起刷起来!