Leetcode - Random Pick Index

weixin_34050427發表於2016-10-13

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

相關文章