算法01:二分法(最左索引)实现

二分法(最左索引)实现

二分法

首先看一下Arrays源码中的二分法实现。

// Arrays工具类中的实现
public static int binarySearch(int[] a, int fromIndex, int toIndex,
                                   int key) {
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0(a, fromIndex, toIndex, key);
    }

    // Like public version, but without range checks.
    private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }

返回-(low + 1),low指向的是插入到数组的位置,这个返回值保证了当找不到target时,返回值小于0。

理解:采用了三次if-else语句,找到值则直接返回;当找不到target时,left指向值 > target, right 指向值小于target。


找到target的最左索引

public static int bsLeftMost(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return (left == right && nums[left] == target) ? left : -1;
    }
// eg1
// [1, 1, 2] 1
// [left ... right] = [1, 1, 2] -> [1, 1] -> [1]

// eg2
// [1, 2, 2] 2
// [left ... right] = [1, 2, 2] -> [1, 2] -> [2]

理解:当选取mid时,观察到left < right时,mid < right恒成立,只需使用二次if-else,即可保证left实现增长(即[left, right] 区间在缩小)。与三次if-else相比,当找到target后,[left, righ] 依旧缩小到长度为1。

当输入数组长度为0时,直接返回-1;


找到target的最右索引

根据如上的思路只需要保证每次都缩小[left ... right],并且当找到target时,(在找到下一个更优解target时,此指针指向target不变)。在上例中取反即可。

public static int bsRightMost(int[] nums, int target) {
    int n = nums.length;
    int left = 0, right = n - 1;
    while (left < right) {
        int mid = (left + right + 1) / 2;
        if (nums[mid] > target) {
            right = mid - 1;
        } else {
            left = mid;
        }
        System.out.print("left = " + left);
        System.out.println(", right = " + right);
    }
    return (left == right && nums[left] == target) ? left : -1;
}

练习

5219. Maximum Candies Allocated to K Children

class Solution {
    // true ture false false false
    public int maximumCandies(int[] candies, long k) {
        long sum = 0;
        for (int candy : candies) sum += candy;
        Arrays.sort(candies);
        long max = sum / k;
        if (max == 0L) return 0;
        int n = candies.length;
        int left = 0;
        int right = (int) max;
        while (left < right) {
            int mid = (left + right + 1) / 2;
            if (!helper(candies, k, mid)) {
                right = mid - 1;
            } else {
                left = mid;
            }
        }
        return left;
    }

    public boolean helper(int[] candies, long k, int max) {
        int n = candies.length;
        if (max == 0L) return true;
        long heap = 0;
        for (int i = n-1; i >= 0; i--) {
            long prov = candies[i] / max;
            heap += prov;
            if (heap >= k) {
                return true;
            }
            if (heap + prov * i < k) {
                return false;
            }
        }
        return false;
    }
}
posted @   桦说编程  阅读(63)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示