File tree Expand file tree Collapse file tree 1 file changed +36
-5
lines changed
app/src/main/java/assignment Expand file tree Collapse file tree 1 file changed +36
-5
lines changed Original file line number Diff line number Diff line change 1
1
package assignment ;
2
2
3
3
public class Set <T > {
4
- public void add ( T item ) {}
4
+ private T [] set = ( T []) new Object [ 32 ];
5
5
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
+ }
7
25
return false ;
8
26
}
9
27
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
+ }
11
36
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 ;
14
45
}
15
46
}
You can’t perform that action at this time.
0 commit comments