Skip to content

Commit 207abd0

Browse files
solve task 380
1 parent 52ee8c7 commit 207abd0

3 files changed

Lines changed: 85 additions & 0 deletions

File tree

PROGRESS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
| leetcode | easy | 0283. move zeroes | Java | [Solution.java](leetcode/java/easy/0283-move-zeroes/Solution.java) | [notes.md](leetcode/java/easy/0283-move-zeroes/notes.md) |
99
| leetcode | easy | 1446. consecutive characters | Java | [Solution.java](leetcode/java/easy/1446-consecutive-characters/Solution.java) | [notes.md](leetcode/java/easy/1446-consecutive-characters/notes.md) |
1010
| leetcode | medium | 0049. group anagrams | Java | [Solution.java](leetcode/java/medium/0049-group-anagrams/Solution.java) | [notes.md](leetcode/java/medium/0049-group-anagrams/notes.md) |
11+
| leetcode | medium | 0380. insert delete getrandom o1 | Java | [Solution.java](leetcode/java/medium/0380-insert-delete-getrandom-o1/Solution.java) | [notes.md](leetcode/java/medium/0380-insert-delete-getrandom-o1/notes.md) |
1112
| leetcode | medium | 0443. string compression | Java | [Solution.java](leetcode/java/medium/0443-string-compression/Solution.java) | [notes.md](leetcode/java/medium/0443-string-compression/notes.md) |
1213
| leetcode | medium | 0560. subarray sum equals k | Java | [Solution.java](leetcode/java/medium/0560-subarray-sum-equals-k/Solution.java) | [notes.md](leetcode/java/medium/0560-subarray-sum-equals-k/notes.md) |
1314
| leetcode | medium | 1493. longest subarray of 1s after deleting one element | Java | [Solution.java](leetcode/java/medium/1493-longest-subarray-of-1s-after-deleting-one-element/Solution.java) | [notes.md](leetcode/java/medium/1493-longest-subarray-of-1s-after-deleting-one-element/notes.md) |
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class RandomizedSet {
2+
private HashMap<Integer, Integer> mainSet;
3+
private ArrayList<Integer> randomArr;
4+
5+
public RandomizedSet() {
6+
this.mainSet = new HashMap<>();
7+
this.randomArr = new ArrayList<>();
8+
}
9+
10+
public boolean insert(int val) {
11+
if(mainSet.containsKey(val)){
12+
return false;
13+
}
14+
if(randomArr.size() <= mainSet.size()){
15+
randomArr.add(val);
16+
mainSet.put(val, randomArr.size() - 1);
17+
}else{
18+
int size = mainSet.size();
19+
randomArr.set(mainSet.size(), val);
20+
mainSet.put(val, size);
21+
}
22+
return true;
23+
}
24+
25+
public boolean remove(int val) {
26+
if(!mainSet.containsKey(val)){
27+
return false;
28+
}
29+
if(mainSet.get(val) + 1 == mainSet.size()){
30+
mainSet.remove(val);
31+
}else{
32+
int pos = mainSet.get(val);
33+
int endVal = randomArr.get(mainSet.size() - 1);
34+
mainSet.put(endVal, pos);
35+
randomArr.set(pos, endVal);
36+
mainSet.remove(val);
37+
}
38+
return true;
39+
}
40+
41+
public int getRandom() {
42+
Random rand = new Random();
43+
int max = mainSet.size() - 1;
44+
int min = 0;
45+
int randomNum = rand.nextInt(max - min + 1) + min;
46+
return randomArr.get(randomNum);
47+
}
48+
}
49+
50+
/**
51+
* Your RandomizedSet object will be instantiated and called as such:
52+
* RandomizedSet obj = new RandomizedSet();
53+
* boolean param_1 = obj.insert(val);
54+
* boolean param_2 = obj.remove(val);
55+
* int param_3 = obj.getRandom();
56+
*/
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# 380. Insert Delete GetRandom O(1)
2+
3+
## link
4+
LeetCode: https://leetcode.com/problems/insert-delete-getrandom-o1/
5+
6+
## Pattern
7+
- Array
8+
- HashMap
9+
10+
## Idea
11+
### Rus
12+
Необычная задача относительно других. Здесь необходимо сделать реализацию структуры данных.
13+
Чтоб получить констатный вставку и удаление, можно использовать просто `HashSet`. Но главная проблема это получить рандомный константный доступ к элементу. Так как из HashSet или HashMap нельзя напрямую получить рандомный элемент за констаное время.
14+
Поэтому идея хранить элементы одновременно в массиве и в HashMap. Массив будет просто по порядку их хранить. При добавлении в конец ставим, при удалении убираем элемент и на его место ставим последний элемент массива. При доступе просто выбираем рандомный индекс и получаем его.
15+
А вот HashMap будет хранить в ключах значения. А в значениях индекс в массиве где они. Это нужно чтоб можно было легко проверять есть элемент или нет. И удалять также быстро не проходясь по всему массиву.
16+
Для того чтоб понимать где конец массива, можно использовать длину HashMap. Она будет значит сколько элементов сейчас у нас.
17+
### Eng
18+
An unusual task relative to others. Here it is necessary to implement the data structure.
19+
To get the correct insertion and deletion, you can simply use a `HashSet'. But the main problem is to get random constant access to the element. Since you cannot directly get a random element from a HashSet or HashMap in a given time.
20+
Therefore, the idea is to store the elements simultaneously in an array and in a HashMap. The array will simply store them in order. When adding to the end, we put, when deleting, we remove the element and put the last element of the array in its place. When accessing, we simply select a random index and get it.
21+
But HashMap will store the values in the keys. And in the values, the index in the array is where they are. This is necessary so that you can easily check whether there is an element or not. And delete it quickly, too, without going through the entire array.
22+
In order to understand where the end of the array is, you can use the HashMap length. It will mean how many elements we have now.
23+
24+
## Complexity
25+
- Time: O(1)
26+
- Space: O(n)
27+
28+
## Problems

0 commit comments

Comments
 (0)