Golang simple reservoir sampling solution


  • 0
    R
    import "math/rand"
    
    type Solution struct {
        numz []int
    }
    
    
    func Constructor(nums []int) Solution {
        return Solution{nums}
    }
    
    
    func (this *Solution) Pick(target int) int {
        total := 0
        res := -1
        for i:=0; i <len(this.numz); i++ {
            if this.numz[i] == target {
                total++
                if rand.Intn(total) == 0 {
                    res = i
                }
                
            }
        }
        return res
    }
    

Log in to reply
 

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