380 Insert Delete GetRandom O
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了380 Insert Delete GetRandom O相关的知识,希望对你有一定的参考价值。
https://www.youtube.com/watch?v=y240Qh9H9uk https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/380.%20Insert%20Delete%20GetRandom%20O(1).java这个答案 就是花花讲的 java 版本。 用 hashmap 和 arraylist . 删除的时候,把要删除的元素和数组的最后一位元素的数值换一下 然后可以删掉数组的最后一个元素 还有哈希表里要删的元素 Line 4: error: <identifier> expected class RandomizedCollection { /** Initialize your data structure here. */ private HashMap<Integer, Integer>() map; private List<Integer> list; Random random; ////////// public RandomizedCollection() { map = new HashMap<>(); list = new ArrayList<>(); random = new Random(); } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)){ map.put(val, list.size()); list.add(val); return true; }else{ return false; } } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ public boolean remove(int val) { if(!map.containsKey(val)){ return false; }else{ // contains val int pos = map.get(val); int lastVal = list.get(list.size() - 1); map.put(lastVal, pos); list.set(pos, lastVal); map.remove(val); list.remove(list.size()-1); return true; } } /** Get a random element from the collection. */ public int getRandom() { return list.get(random.nextInt(list.size()));///// list.get(random.nextInt(list.size())) } }
以上是关于380 Insert Delete GetRandom O的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 380. Insert Delete GetRandom O
380. Insert Delete GetRandom O
LeetCode 380. Insert Delete GetRandom O