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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
| public class SparseArrayEntry{
private int row;
private int col;
private int value;
public SparseArrayEntry(int r, int c, int v){
this.row = r;
this.col = c;
this.value = v;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
public int getValue(){
return value;
}
public void setCol(int c) {
this.col = c;
}
public void setRow(int r) {
this.row = r;
}
}
public class SparseArray {
private int numRows;
private int numCols;
private List<SparseArrayEntry> entries;
public SparseArray(ArrayList<SparseArrayEntry> entries, int numRows, int numCols) {
this.entries = entries;
this.numRows = numRows;
this.numCols = numCols;
}
// part a
public int getValueAt(int row, int col){
for (SparseArrayEntry entry : entries){ // entries stores ArrayList not 2D array!!
if (entry.getRow() == row && entry.getCol() == col){
return entry.getValue();
}
}
return 0;
}
// part b
public void removeColumn(int col){
//iterating from the end of the list to avoid issues related to removing entries in the middle of the list and make the logic simpler.
for (int i = entries.size() - 1; i >= 0; i--){
SparseArrayEntry entry = entries.get(i);
if (entry.getCol() == col){
entries.remove(i);
}
else if(entry.getCol() > col){
entry.setCol(entry.getCol() - 1);
}
}
numCols--;
}
public void printArray() {
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(getValueAt(i, j) + " ");
}
System.out.println();
}
}
// test
public static void main(String[] args) {
ArrayList<SparseArrayEntry> entries = new ArrayList<>();
//adds entries where sparse array is not 0
entries.add(new SparseArrayEntry(1, 1, 4));
entries.add(new SparseArrayEntry(2, 4, 3));
entries.add(new SparseArrayEntry(2, 2, 9));
//creates array
SparseArray arr = new SparseArray(entries, 5, 5);
// test part a
System.out.println("(1,1): " + arr.getValueAt(1, 1));
// test part b
arr.printArray();
arr.removeColumn(2);
System.out.println("Remove Column 2:");
arr.printArray();
}
}
SparseArray.main(null);
|