给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您能够假设给定的数字必定存在于数组中。git
注意:github
数组大小可能很是大。 使用太多额外空间的解决方案将不会经过测试。golang
示例:面试
int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) 应该返回索引 2,3 或者 4。每一个索引的返回几率应该相等。 solution.pick(3); // pick(1) 应该返回 0。由于只有nums[0]等于1。 solution.pick(1);
// Solution defines a structure type Solution struct { nums []int } // Constructor constructs a object func Constructor(nums []int) Solution { return Solution{ nums: nums, } } // Pick returns index number that target at nums Randomly. func (s *Solution) Pick(target int) int { res := []int{} for i, v := range s.nums { if v == target { res = append(res, i) } } rand.Seed(time.Now().UnixNano()) return res[rand.Intn(len(res))] }
本文为原创文章,转载注明出处,欢迎扫码关注公众号
楼兰
或者网站
https://lovecoding.club,第一时间看后续精彩文章,以为好的话,顺手分享到朋友圈吧,感谢支持。