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);
     */
  • 相关阅读:
    常用的正则表达式
    vue多页面应用
    webpack + jquery + bootstrap 环境配置
    Goroutine的几个例子
    设置css通用字体
    简单的gulpfile.js参数配置
    1:时间戳转换成年月日函数,2:url截取参数方法,3:弹窗自定义方法 4:点击按钮加入购物车
    github上比较全的知识
    秒杀倒计时
    正则校验手机号码并获取手机验证码倒计时的实例
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5863566.html
Copyright © 2011-2022 走看看