給定一個可能含有重複元素的整數數組,要求隨機輸出給定的數字的索引。 您能夠假設給定的數字必定存在於數組中。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))]
}
複製代碼
本文爲原創文章,轉載註明出處,歡迎掃碼關注公衆號
樓蘭
或者網站lovecoding.club,第一時間看後續精彩文章,以爲好的話,順手分享到朋友圈吧,感謝支持。數組