随机输出带权重数组中的值(百度二面算法题目)

来源:互联网 发布:淘宝如何取消超级推广 编辑:程序博客网 时间:2024/06/02 06:08
  • 题目:给定一个数组,每个值都是一个权值。随机返回数组中的数,要求权值高的相应的返回的概率高。比如现在数组存储了音乐的打分,要求随机返回数组中一个数的值。(假设数组中的值都是整数)
  • 思路: 以 A:3, B:5, C:2,D:1 四条记录上随机选取一个值输出为例,(是否以权重排序这个无所谓)
    对于
    A 3
    B 5
    C 2
    D 1
    首先,将第n行的数值赋为第n行加第n-1行的,递归执行,如下:
    A 3
    B 8
    C 10
    D 11

可以看出,数组变换后,当产生[1,3]的随机数时,对应输出3,当产生[4,8]的随机数时,对应输出5,当产生[9,10]的随机数时,对应输出2,当产生11时,对应输出1。

代码块

代码块语法遵循标准markdown代码,例如:

import java.util.Random;/** * Created by happy on 17/5/14. */public class Random_weighted_val {    public static void main(String[] args) {        int n = 0;        int iter = 100;        int[] nums = {3, 5, 2, 1};        //不能写成int[] nums_copy=nums,否则nums一变,nums_copy也会跟着变        int[] nums_copy=nums.clone();        int sum = 0;        //记录数组中所有权重的和        for (int i = 0; i < nums.length; i++) {            sum += nums[i];        }        expand(nums);        Random ran = new Random();        for (int i = 0; i<iter; i++) {            n = ran.nextInt(sum)+1; //生成[1,sum]的随机数            //System.out.print(n+1 + " ");            int pos = getRandom(nums,0,nums.length-1,n);            System.out.print(n+" "+nums_copy[pos]+" ");            System.out.println();        }    }    //给定一个随机数,判断其落在哪个区间    public static int getRandom(int[] nums, int begin, int end, int ranNum) {        if (begin >= end)            return begin;//返回条件为begin >= end        int mid = (end + begin) / 2;        if (ranNum > nums[mid]) {            return getRandom(nums, mid+1, end, ranNum); //注意mid+1        } else {            return getRandom(nums, begin, mid, ranNum);//注意mid        }    }    public static int[] expand(int[] nums){        for(int i=1;i<nums.length;i++){            nums[i]=nums[i]+nums[i-1];        }        return nums;    }}
0 0
原创粉丝点击