​LeetCode刷题实战398:随机数索引

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 随机数索引,我们先来看题面:

https://leetcode-cn.com/problems/integer-replacement/

Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Implement the Solution class:

Solution(int[] nums) Initializes the object with the array nums.

int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.

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

注意:

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

示例

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);

解题

https://www.freesion.com/article/3565759878/

解题思路:

首先看题、分析题意,我们可以明确1个关键点:

1.如何实现随机返回索引

既然,我们已经分析出来题目的关键任务了,下面我们就可以开始思考实现了。

我们采用算法与数据结构的思路来剖析一下这题,

数据结构:

要实现对数据的操作,我们要先明确存储数据的数据结构。

该题的数据结构的作用:

1.设置一个ArrayList来保存索引数

2.申请一个随机数对象,用于生成随机数

算法:

既然明确了我们的数据结构,我们就可以开始我们的算法分析了。

1.对象初始化。

2.遍历数组,寻找索引,保存入arrayList。

3.利用随机数,随机在arrayList取得一个索引数

import java.util.ArrayList;
import java.util.Random;

class Solution {
    ArrayList<Integer> arrayList=new ArrayList<>();
    int []nums;
    public Solution(int[] nums) {
        this.nums=new int[nums.length];
        this.nums=nums;
    }

    public int pick(int target) {
        Random random=new Random();
        for(int i=0;i<this.nums.length;i++){
            if(target==this.nums[i]){
                arrayList.add(i);//保存索引
            }
        }
        //返回[0,arrayList.size()-1]的正整数
        return arrayList.get(random.nextInt(arrayList.size()));
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-380题汇总,希望对你有点帮助!

LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素

LeetCode刷题实战382:链表随机节点

LeetCode刷题实战383:赎金信

LeetCode刷题实战384:打乱数组

LeetCode刷题实战385:迷你语法分析器

LeetCode刷题实战386:字典序排数

LeetCode刷题实战387:字符串中的第一个唯一字符

LeetCode刷题实战388:文件的最长绝对路径

LeetCode刷题实战389:找不同

LeetCode刷题实战390:消除游戏

LeetCode刷题实战391:完美矩形

LeetCode刷题实战392:判断子序列

LeetCode刷题实战393:UTF-8 编码验证

LeetCode刷题实战394:字符串解码

LeetCode刷题实战395:至少有 K 个重复字符的最长子串

LeetCode刷题实战396:旋转函数

LeetCode刷题实战397:整数替换

ee877faa6006821ca74de651e1a7eba9.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值