Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f7eb6f8

Browse files
committed
feat: update solution to leetcode problem: No.0705
1 parent d635a4c commit f7eb6f8

File tree

1 file changed

+60
-0
lines changed
  • solution/0700-0799/0705.Design HashSet

1 file changed

+60
-0
lines changed

‎solution/0700-0799/0705.Design HashSet/README.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ class MyHashSet:
8484

8585
<!-- 这里可写当前语言的特殊实现逻辑 -->
8686

87+
- 可以一次性开辟一个大的数组,存放所有元素。
88+
8789
```java
8890
class MyHashSet {
8991

@@ -117,6 +119,64 @@ class MyHashSet {
117119
*/
118120
```
119121

122+
- 也可以开辟一个大小为 `SIZE` 的数组,数组的每个位置是一个链表。
123+
124+
```java
125+
class MyHashSet {
126+
127+
private static final int SIZE = 1000;
128+
private LinkedList[] data;
129+
130+
/** Initialize your data structure here. */
131+
public MyHashSet() {
132+
data = new LinkedList[SIZE];
133+
Arrays.fill(data, new LinkedList<Integer>());
134+
}
135+
136+
public void add(int key) {
137+
int index = hash(key);
138+
Iterator<Integer> iterator = data[index].iterator();
139+
while (iterator.hasNext()) {
140+
Integer e = iterator.next();
141+
if (e == key) return;
142+
}
143+
data[index].addFirst(key);
144+
}
145+
146+
public void remove(int key) {
147+
int index = hash(key);
148+
ListIterator<Integer> iterator = data[index].listIterator();
149+
while (iterator.hasNext()) {
150+
Integer e = iterator.next();
151+
if (e == key) iterator.remove();
152+
}
153+
}
154+
155+
/** Returns true if this set contains the specified element */
156+
public boolean contains(int key) {
157+
int index = hash(key);
158+
Iterator<Integer> iterator = data[index].iterator();
159+
while (iterator.hasNext()) {
160+
Integer e = iterator.next();
161+
if (e == key) return true;
162+
}
163+
return false;
164+
}
165+
166+
private int hash(int key) {
167+
return key % SIZE;
168+
}
169+
}
170+
171+
/**
172+
* Your MyHashSet object will be instantiated and called as such:
173+
* MyHashSet obj = new MyHashSet();
174+
* obj.add(key);
175+
* obj.remove(key);
176+
* boolean param_3 = obj.contains(key);
177+
*/
178+
```
179+
120180
### **...**
121181

122182
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /