美文网首页
380. Insert Delete GetRandom O(1

380. Insert Delete GetRandom O(1

作者: 夜皇雪 | 来源:发表于2016-11-27 04:06 被阅读0次
public class RandomizedSet {
    ArrayList<Integer> nums;
    HashMap<Integer,Integer> map;
    java.util.Random rand=new java.util.Random();
    /** Initialize your data structure here. */
    public RandomizedSet() {
        nums=new ArrayList<>();
        map=new HashMap<>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if(map.containsKey(val)) return false;
        map.put(val,nums.size());
        nums.add(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if(!map.containsKey(val)) return false;
        int num=map.get(val);
        if(num<nums.size()-1){
            int lastone=nums.get(nums.size()-1);
            nums.set(num,lastone);
            map.put(lastone,num);
        }
        map.remove(val);
        nums.remove(nums.size()-1);
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        return nums.get(rand.nextInt(nums.size()));
    }
}

相关文章

网友评论

      本文标题:380. Insert Delete GetRandom O(1

      本文链接:https://www.haomeiwen.com/subject/rnngpttx.html