怎么入侵网站后台,曲阜网站建设,建设银行北京东四支行网站,网站h1标签的应用380. O(1 时间插入、删除和获取随机元素 原题链接#xff1a;完成情况#xff1a;解题思路#xff1a;参考代码#xff1a; 原题链接#xff1a;
380. O(1) 时间插入、删除和获取随机元素
https://leetcode.cn/problems/insert-delete-getrandom-o1/description/
完成… 380. O(1 时间插入、删除和获取随机元素 原题链接完成情况解题思路参考代码 原题链接
380. O(1) 时间插入、删除和获取随机元素
https://leetcode.cn/problems/insert-delete-getrandom-o1/description/
完成情况 解题思路
思路都在代码里。
参考代码
package 西湖算法题解___中等题;import java.util.*;public class __380__O1时间插入删除和获取随机元素__深入理解 {class RandomizedSet {ListInteger nums;MapInteger,Integer indices;Random random;public RandomizedSet() {nums new ArrayListInteger();indices new HashMapInteger,Integer();random new Random();}public boolean insert(int val) {if (indices.containsKey(val)){return false;}//得有index去记录数组位置同时又得有Map去 保存对应的keyvalue则可以达到O1int index nums.size();nums.add(val);indices.put(val,index);return true;}public boolean remove(int val) {if (!indices.containsKey(val)){return false;}int index indices.get(val);int last nums.get(nums.size() - 1);nums.set(index,last); //两处value互换一下indices.put(last,index);nums.remove(nums.size()-1); //删除最后一个位置indices.remove(val); //Map里也删掉val这个keyreturn true;}public int getRandom() {int randomIndex random.nextInt(nums.size()); //生成一个Int类型的[0,nums.size)这个范围内的一个随机数。return nums.get(randomIndex);}}}