Skip to content

Commit 816dc81

Browse files
committed
homework completed
1 parent b33c481 commit 816dc81

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed
Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,46 @@
11
package assignment;
22

33
public class Set<T> {
4-
public void add(T item) {}
4+
private T[] set = (T[]) new Object[32];
55

6-
public boolean contains(T item) {
6+
public void add(T item) { // O(n)
7+
int firstFreeSpot = -1; // O(1)
8+
for (int i = 0; i<set.length; i++) { // O(n)
9+
if (set[i] == item) { // O(1)
10+
return;
11+
}
12+
if (set[i] == null && firstFreeSpot == -1) { // O(1)
13+
firstFreeSpot = i; // O(1)
14+
}
15+
}
16+
set[firstFreeSpot] = item; // O(1)
17+
}
18+
19+
public boolean contains(T item) { // O(n)
20+
for (T currentItem: set) { // O(n)
21+
if (currentItem == item) { // O(1)
22+
return true;
23+
}
24+
}
725
return false;
826
}
927

10-
public void remove(T item) {}
28+
public void remove(T item) { // O(n)
29+
for (int i = 0; i < set.length; i++) { // O(n)
30+
if (set[i] == item) { // O(1)
31+
set[i] = null; // O(1)
32+
return;
33+
}
34+
}
35+
}
1136

12-
public int size() {
13-
return 0;
37+
public int size() { // O(n)
38+
int nullCount = 0; // O(1)
39+
for (int i = 0; i < set.length; i++) { // O(n)
40+
if (set[i] == null) { // O(1)
41+
nullCount++; // O(1)
42+
}
43+
}
44+
return set.length - nullCount;
1445
}
1546
}

0 commit comments

Comments
 (0)