力扣labuladong一刷day23天带权重的随机选择算法

力扣labuladong一刷day23天带权重的随机选择算法

一、528. 按权重随机选择

题目链接:https://leetcode.cn/problems/random-pick-with-weight/
思路:要求按权重随机选择,可以使用前缀和数组,然后random出一个数,寻找这个数在前缀和数组里大于等于他最小的那个数的索引,即可。前缀和数组是每一个权重的累加,这样落点在两点之间也符合权重要求。

class Solution {
    private int[] preSum;
    private Random random = new Random();
    public Solution(int[] w) {
        preSum = new int[w.length+1];
        for (int i = 1; i < preSum.length; i++) {
            preSum[i] = preSum[i-1] + w[i-1];
        }
    }

    public int pickIndex() {
        int target = random.nextInt(preSum[preSum.length - 1]) + 1;
        return getLeft(preSum, target) - 1;
    }

    int getLeft(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid - 1;
            }else {
                left = mid + 1;
            }
        }
        return left;
    }
}

你可能感兴趣的:(力扣算法题,算法,leetcode,职场和发展)