Leetcode528 按权重随机选择 前缀和上的二分查找

  概率的映射可以转化为前缀和上的区间映射,在前缀和中进行二分查找即可在相应概率下返回坐标。

class Solution {

        int sum = 0;
        List<Integer> psum = new LinkedList<Integer>();
        Random random = new Random();

        public Solution(int[] w) {
            for (int num : w) {
                sum += num;
                psum.add(sum);
            }
        }

        public final int pickIndex() {
            int tar = random.nextInt(sum);
            int begin = 0, end = psum.size() - 1;
            while (begin != end) {
                int mid = (begin + end) / 2;
                if (psum.get(mid) <= tar) begin = mid + 1;
                else end = mid;
            }
            return begin;
        }
    }

 

posted @ 2020-11-11 00:13  牛有肉  阅读(119)  评论(0编辑  收藏  举报