- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1570.java
92 lines (83 loc) · 3.21 KB
/
_1570.java
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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.List;
publicclass_1570 {
publicstaticclassSolution1 {
/*
* This is a brute force but accepted solution.
*/
classSparseVector {
int[] vector;
SparseVector(int[] nums) {
this.vector = nums;
}
// Return the dotProduct of two sparse vectors
publicintdotProduct(SparseVectorvec) {
int[] incoming = vec.vector;
intdotProduct = 0;
for (inti = 0; i < vector.length; i++) {
dotProduct += incoming[i] * this.vector[i];
}
returndotProduct;
}
}
}
publicstaticclassSolution2 {
/*
* More optimal solution:
* 1. use a map to store only non-zero values to save space;
* 2. loop through the smaller list;
* 3. use binary search to find the corresponding index in the bigger list if it exists;
*/
classSparseVector {
privateList<int[]> indexAndNumList;
SparseVector(int[] nums) {
this.indexAndNumList = newArrayList<>();
for (inti = 0; i < nums.length; i++) {
if (nums[i] != 0) {
this.indexAndNumList.add(newint[] {i, nums[i]});
}
}
}
// Return the dotProduct of two sparse vectors
publicintdotProduct(SparseVectorvec) {
List<int[]> incoming = vec.indexAndNumList;
if (incoming.size() < this.indexAndNumList.size()) {
returndotProduct(incoming, this.indexAndNumList);
} else {
returndotProduct(this.indexAndNumList, incoming);
}
}
privateintdotProduct(List<int[]> smaller, List<int[]> bigger) {
intproduct = 0;
for (int[] indexAndNum : smaller) {
int[] exists = binarySearch(bigger, indexAndNum[0]);
if (indexAndNum[0] == exists[0]) {
product += indexAndNum[1] * exists[1];
}
}
returnproduct;
}
privateint[] binarySearch(List<int[]> indexAndNumList, inttarget) {
intleft = 0;
intright = indexAndNumList.size() - 1;
int[] result = newint[] {-1, 0};
if (indexAndNumList.get(right)[0] < target
|| indexAndNumList.get(left)[0] > target) {
returnresult;
}
while (left <= right) {
intmid = left + (right - left) / 2;
if (indexAndNumList.get(mid)[0] == target) {
returnindexAndNumList.get(mid);
} elseif (indexAndNumList.get(mid)[0] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
returnnewint[] {-1, 0};
}
}
}
}