my java code,but it cost too much time(400ms),why? used reservoir algorithm


  • 0
    F

    public class Solution {

    public Solution(int[] nums) {
        Nums = nums;
        raddom = new Random();
    }
    
    public int pick(int target) {
        int curent = -1;
        int count = 1;
        for(int i=0;i<Nums.length;i++)
        {
            if(Nums[i] == target)
            {
                if(raddom.nextInt(count) ==0)
                {
                    curent = i;                
                }
                count++;
            }
        }
        return curent;
    }
    private int result;
    private int[] Nums;
    private Random raddom;
    

    }

    /**

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.