151.Insert Delete GetRandom O(1) - Duplicates allowed

本文介绍了一个支持插入、删除和随机返回元素的数据结构实现。该结构允许元素重复,并在平均时间复杂度为O(1)的情况下完成操作。通过示例展示了如何使用这个随机集合。

Design a data structure that supports all following operations in average O(1) time.

Note: Duplicate elements are allowed.
  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

Subscribe to see which companies asked this question

分析,与前一道题目类似,不一样的地方在于,集合中可以存在重复的元素,但是在插入的时候如果已存在需要插入的val时,则返回false,但是还是要把val插入到集合中。

 ArrayList<Integer> list;
	
	  /** Initialize your data structure here. */
    public RandomizedCollection() {
    	list = new ArrayList<Integer>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        boolean flag = !list.contains(val);
        list.add(val);
        return flag;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
    	if(!list.contains(val)){
    		return false;
    	}else{
    		list.remove((Integer)val);
    		return true;
    	}
    }
    
    /** Get a random element from the set. */
    public int getRandom() {

    	if (list.size() == 1) {// 如果全排列的个数小于等于1个,则只需要返回base数组即可。
			return  list.get(0);
		}
		/* 随机生成一个下标 */
		Random random = new Random();
		int i = random.nextInt(list.size());
		return list.get(i);
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值