zoukankan      html  css  js  c++  java
  • 插入、删除和随机查询时间复杂度都为O(1) leetcode 381

    插入、删除和随机查询时间复杂度都为O(1)

    解题思路:map+list

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Random;
    
    class RandomizedCollection {
        public static void main(String[] args) {
            RandomizedCollection s = new RandomizedCollection();
            s.insert(1);
            s.remove(1);
            s.insert(1);
            System.out.println(s.list);
            
        }
        public Map<Integer,List<Integer>> map = new HashMap<>();
        public List<Integer> list = new ArrayList<>();
        /** Initialize your data structure here. */
        public RandomizedCollection() {
            
        }
        
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        public boolean insert(int val) {
            list.add(val);
            List<Integer> temp = map.get(val);
            if(temp==null){
                temp = new ArrayList<>();
                temp.add(list.size()-1);
                map.put(val,temp);
                return true;
            }else{
                temp.add(list.size()-1);
                return false;
            }
            
        }
        
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        public boolean remove(int val) {
            List<Integer> temp = map.get(val);
            if(temp==null){
                return false;
            }
            int item = temp.remove(0);
            if(temp.size()==0) {
                map.remove(val);
            }
            if(list.size()-1==item) {
                list.remove(item);
            }else {
                Integer lastItem = list.remove(list.size()-1);//最后一个元素的内容
                list.set(item, lastItem);
                //对结尾元素的调整
                temp = map.get(lastItem);
                temp.remove((Integer)list.size());//这个过程还是比较耗时的
                temp.add(item);
            }
            return true; 
        }
        
        /** Get a random element from the collection. */
        public int getRandom() {
            Random random = new Random();
            int o = random.nextInt(list.size());
            return list.get(o);
        }
    }
  • 相关阅读:
    String 尺取法
    dos 命令
    又见01背包
    01串
    Python-Matplotlib 10 面向对象 VS Matlab Style
    [ 转 ] Fiddler 教程
    Android 查看设备文件
    Python-Matplotlib 9 颜色和样式 [r]
    Python-Matplotlib 8 箱形图
    Python-Matplotlib 7 饼状图
  • 原文地址:https://www.cnblogs.com/erdanyang/p/11506547.html
Copyright © 2011-2022 走看看