Leetcode - Random Pick Index

My code:

public class Solution {
    int[] nums;
    int result = Integer.MAX_VALUE;
    Random r;
    
    public Solution(int[] nums) {
        this.nums = nums;
        r = new Random();
    }
    
    public int pick(int target) {
        int c = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                c++;
                if (r.nextInt(c) == 0) {
                    result = i;
                }
            }
        }
        
        return result;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */

差不多的做法。

Anyway, Good luck, Richardo! — 10/12/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/a4b368d9a0da
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞