zoukankan      html  css  js  c++  java
  • <Random> 384 398

    384. Shuffle an Array

    random.nextInt(n) 返回[0, n) 的随机数,故要+1;

    class Solution {
        
        private int[] nums;
        private Random random;
        
        public Solution(int[] nums) {
            this.nums = nums;
            random = new Random();
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return nums;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            if(nums == null)    return null;
            
            int[] a = nums.clone();
            for(int j = 1; j < a.length; j++){
                int i = random.nextInt(j + 1);
                swap(a, i , j);
            }
            return a;
        }
        
        private void swap(int[] a, int i, int j){
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
    }

    398. Random Pick Index

    2 : It's probability of selection is 1 * (1/2) * (2/3) = 1/3
    3 : It's probability of selection is (1/2) * (2/3) = 1/3
    4 : It's probability of selection is just 1/3

    class Solution {
    
        int[] nums;
        Random random;
        
        public Solution(int[] nums) {
            this.nums = nums;
            this.random = new Random();
        }
        
        public int pick(int target) {
            int res = -1;
            int count = 0;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] != target)
                    continue;
                if(random.nextInt(++count) == 0)
                    res = i;
            }
            return res;
        }
    }
  • 相关阅读:
    常用正则表达式
    Python的ASCII, GB2312, Unicode , UTF-8 相互转换
    Java 获取Linux 的IP地址
    MySql 取一天的开始时间和结束时间
    MyCat 主键ID自增长配置
    helm安使用
    Photoshop 7.0 安装及注册方法
    photoshop7.0 排版一寸照片、2寸照片
    DevOps工具链
    traefik安装
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11840861.html
Copyright © 2011-2022 走看看