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;
        }
    }
  • 相关阅读:
    php mysql基本操作
    php之curl的使用
    linux下操作php和apache
    ThinkPHP_目录结构和初始化
    ubuntu下计划任务cron的使用
    linux下操作mysql
    php操作csv文件
    HTML5基础一:常用布局标签
    liunx下shell脚本的创建和使用
    一个完整的ajax登陆实例
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11840861.html
Copyright © 2011-2022 走看看