zoukankan      html  css  js  c++  java
  • 398. Random Pick Index

    Question

    398. Random Pick Index

    Solution

    思路:重点是如果数据中有多个数target相等,要从这些数中随机取一个,根据例题

    假设输入是:
    int[] nums = new int[]{1, 2, 3, 3, 3};
    int target = 3;
    
    模拟:
    1  != target pass
    2  != target pass
    3  == target pick的概率 nextInt(1)==0的概率 1,返回这个index的概念是1 - 1/3 -1/3 = 1/3
    3  == target pick的概率 nextInt(2)==0的概率 1/2, 返回这个index的概率是1/2 * 2/3 = 1/3
    3  == target pick的概率 nextInt(3)==0的概率 1/3, 返回这个index的概率是1/3
    
    

    Java实现:

    class Solution {
        private int[] nums;
        private Random random;
        
        public Solution(int[] nums) {
            this.nums = nums;
            random = new Random();
        }
        
        public int pick(int target) {
            int index = -1;
            int count = 0;
            for (int i=0; i<nums.length; i++) {
                if (nums[i] == target && random.nextInt(++count) == 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);
     */
    

    Reference

  • 相关阅读:
    Windows下载Vim
    分享:分享几个程序员使用的网站
    分享:C语言大礼包(PDF)
    将vscode打造成强大的C/C++ IDE
    最适合做C/C++开发的IDE
    bzoj 2244
    bzoj 1492
    bzoj 3262
    bzoj 1176
    bzoj 2961
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9182607.html
Copyright © 2011-2022 走看看