题目地址:
https://www.lintcode.com/problem/insert-delete-getrandom-o1-duplicates-allowed/description
要求实现一个数据结构,能在
O
(
1
)
O(1)
O(1)的时间内完成:
1、添加一个数,如果原本存在则返回false,否则返回true。注意,即使已经存在也要添加;
2、删除一个数,如果原本不存在则返回false,否则返回true;
3、随机返回一个数,每个数的返回的概率应该与其出现的频次成正比。
思路是哈希表 + list。list的作用是存数,而哈希表的作用是存每个数出现在了哪些位置。这样删除一个数的时候,可以先将该数与list最后一个数进行交换,然后删掉,这样可以达到 O ( 1 ) O(1) O(1)的效果。这里尤其需要注意哈希表怎么处理才能不出错。我们可以这样做,如果要删除的数恰好就是list最后一个数,那很容易处理;否则做交换的时候我们就能保证是两个不同的数在交换,这样可以避免出错。代码如下:
import java.util.*;
class RandomizedCollection {
private List<Integer> list;
private Map<Integer, Set<Integer>> map;
private Random random;
/**
* Initialize your data structure here.
*/
public RandomizedCollection() {
list = new ArrayList<>();
map = new HashMap<>();
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) {
// write your code here
boolean res = false;
if (!map.containsKey(val) || map.get(val).isEmpty()) {
map.put(val, new HashSet<>());
res = true;
}
map.get(val).add(list.size());
list.add(val);
return res;
}
/**
* Removes a value from the collection. Returns true if the collection contained the specified element.
*/
public boolean remove(int val) {
// write your code here
if (!map.containsKey(val) || map.get(val).isEmpty()) {
return false;
}
Set<Integer> set = map.get(val);
// 如果val恰好是list最后一个数,则将其删除,下标也对应删除
if (val == list.get(list.size() - 1)) {
set.remove(list.size() - 1);
list.remove(list.size() - 1);
return true;
}
// 否则取出val对应的某个位置,修改list最后一个数字的下标集合
int pos = set.iterator().next();
int last = list.get(list.size() - 1);
map.get(last).remove(list.size() - 1);
map.get(last).add(pos);
// 修改val对应的下标集合
set.remove(pos);
// 做交换,然后删除
Collections.swap(list, pos, list.size() - 1);
list.remove(list.size() - 1);
return true;
}
/**
* Get a random element from the collection.
*/
public int getRandom() {
// write your code here
int r = random.nextInt(list.size());
return list.get(r);
}
}
所有操作时间复杂度 O ( 1 ) O(1) O(1),空间 O ( n ) O(n) O(n)。