398.random-pick-index.go 459 B

12345678910111213141516171819202122
  1. type Solution struct {
  2. index map[int][]int
  3. }
  4. func Constructor(nums []int) Solution {
  5. sol := Solution{index: make(map[int][]int)}
  6. for i, n := range nums {
  7. sol.index[n] = append(sol.index[n], i)
  8. }
  9. return sol
  10. }
  11. func (this *Solution) Pick(target int) int {
  12. arr := this.index[target]
  13. return arr[rand.Intn(len(arr))]
  14. }
  15. /**
  16. * Your Solution object will be instantiated and called as such:
  17. * obj := Constructor(nums);
  18. * param_1 := obj.Pick(target);
  19. */