zoukankan      html  css  js  c++  java
  • LeetCode-Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

    Note:
    The array size can be very large. Solution that uses too much extra space will not pass the judge.

    Example:

    int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1);

    Analysis:

    Get from here:

    https://discuss.leetcode.com/topic/58322/what-on-earth-is-meant-by-too-much-memory/6

    Quote:

    Hi, the question is the same with Q382 Linked List Random Node, the only difference is in this question, we only count the target, and get the random index from the target indices.

    The background of the question is the data stream is very large, and we only need one target index from one data stream, the next data stream is another one, so why do we store every data stream, we just need O(1) space and O(n) time to traverse the first data stream , and O(1) space and O(n) time to traverse the second data stream....

    Have a look at the other guy's solution, it's the same with my explanation:
    https://discuss.leetcode.com/topic/58301/simple-reservoir-sampling-solution

    Solution:

    public class Solution {
        int[] numList;
        Random engine = new Random();
    
        public Solution(int[] nums) {
            numList = nums;
        }
        
        public int pick(int target) {
            int count = 0;
            int index = -1;
            for (int i=0;i<numList.length;i++)
                if (numList[i] == target){
                    count++;
                    int val = engine.nextInt(count);
                    if (val==0){
                        index = i;
                    }
                }
            return index;
        }
    }
    
    /**
     * Your Solution object will be instantiated and called as such:
     * Solution obj = new Solution(nums);
     * int param_1 = obj.pick(target);
     */
  • 相关阅读:
    Elementui:选择框
    Cesium之Cesium3DTileStyle
    Cesium粒子系统:雨雪云效果
    Cesium之3dtiles模型选择问题
    3dtiles贴地
    Android ListView异步加载图片
    Android的硬件加速
    Android ANR
    每天一点Linux 查看Ubuntu的版本号
    Android log system
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5863566.html
Copyright © 2011-2022 走看看