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);
        }
    }
  • 相关阅读:
    《需求工程——软件建模与分析》读后感之三
    项目目标文档
    利益相关者描述案例
    《需求工程——软件建模与分析》读后感之二
    《需求工程——软件建模与分析》读后感之一
    专业实训题目需求分析
    《代码之美》读后感
    计算“1”的数量
    团队冲刺第九天
    linux df 命令
  • 原文地址:https://www.cnblogs.com/erdanyang/p/11506547.html
Copyright © 2011-2022 走看看