forked from liuyubobobo/Play-with-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomizedSet_HashMap.java
73 lines (55 loc) · 1.85 KB
/
RandomizedSet_HashMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/// Leetcode 380. Insert Delete GetRandom O(1)
/// https://leetcode.com/problems/insert-delete-getrandom-o1/description/
///
/// 使用380号问题测试我们的代码
/// 该版本代码使用Java内置的HashMap,作为算法实现的基准
import java.util.Random;
import java.util.HashMap;
import java.util.ArrayList;
public class RandomizedSet_HashMap {
HashMap<String, Integer> map;
ArrayList<Integer> nums;
/** Initialize your data structure here. */
public RandomizedSet_HashMap() {
map = new HashMap();
nums = new ArrayList<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
String key = Integer.toString(val);
if(map.containsKey(key))
return false;
nums.add(val);
int index = nums.size() - 1;
map.put(key, index);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
String key = Integer.toString(val);
if(!map.containsKey(key))
return false;
int index = map.get(key);
map.remove(key);
int num = nums.get(nums.size() - 1);
nums.remove(nums.size() - 1);
if(num != val) {
nums.set(index, num);
map.put(Integer.toString(num), index);
}
return true;
}
/** Get a random element from the set. */
public int getRandom() {
Random random = new Random();
int index = random.nextInt(nums.size());
return nums.get(index);
}
public static void main(String[] args){
RandomizedSet_TrieR rs = new RandomizedSet_TrieR();
rs.insert(0);
rs.remove(0);
rs.insert(-1);
rs.remove(0);
}
}