算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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);
*/
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素
LeetCode刷题实战395:至少有 K 个重复字符的最长子串