36

leetcode.398.随机数索引

 5 years ago
source link: https://studygolang.com/articles/16303?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

题目描述

给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

注意:

数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。

示例:

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))]
}

思路

  • 数组大小可能非常大,尽量不使用太多额外空间,所以Solution对象直接用nums字段
  • 尝试过在Constructor()只遍历一遍nums,创建map存储nums中每个值的索引,但是Leetcode测试一直时间超过限制,可能是因为使用了额外内存吧
  • Pick()中遍历nums,找到target的索引到res中,rand随机选一个索引,返回

GitHub

参考资料

leetcode 398. 随机数索引

本文为原创文章,转载注明出处,欢迎扫码关注公众号 楼兰 或者网站 https://lovecoding.club ,第一时间看后续精彩文章,觉得好的话,顺手分享到朋友圈吧,感谢支持。

1460000017050069


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK