@@ -56,27 +56,84 @@ v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0
56
56
<li><code>0 <= nums1[i], nums2[i] <= 100</code></li>
57
57
</ul >
58
58
59
-
60
59
## 解法
61
60
62
61
<!-- 这里可写通用的实现逻辑 -->
63
62
63
+ 哈希表实现。
64
+
65
+ 用哈希表存储非 0 点的下标与值。求点积时,遍历长度较小的哈希表。
66
+
64
67
<!-- tabs:start -->
65
68
66
69
### ** Python3**
67
70
68
71
<!-- 这里可写当前语言的特殊实现逻辑 -->
69
72
70
73
``` python
71
-
74
+ class SparseVector :
75
+ def __init__ (self , nums : List[int ]):
76
+ self .v = {}
77
+ for i, num in enumerate (nums):
78
+ if num != 0 :
79
+ self .v[i] = num
80
+
81
+ # Return the dotProduct of two sparse vectors
82
+ def dotProduct (self , vec : ' SparseVector' ) -> int :
83
+ res = 0
84
+ if len (self .v) > len (vec.v):
85
+ self .v, vec.v = vec.v, self .v
86
+ for i, num in self .v.items():
87
+ if i not in vec.v:
88
+ continue
89
+ res += num * vec.v[i]
90
+ return res
91
+
92
+
93
+ # Your SparseVector object will be instantiated and called as such:
94
+ # v1 = SparseVector(nums1)
95
+ # v2 = SparseVector(nums2)
96
+ # ans = v1.dotProduct(v2)
72
97
```
73
98
74
99
### ** Java**
75
100
76
101
<!-- 这里可写当前语言的特殊实现逻辑 -->
77
102
78
103
``` java
79
-
104
+ class SparseVector {
105
+
106
+ private Map<Integer , Integer > v;
107
+
108
+ SparseVector (int [] nums ) {
109
+ v = new HashMap<> ();
110
+ for (int i = 0 ; i < nums. length; ++ i) {
111
+ if (nums[i] != 0 ) {
112
+ v. put(i, nums[i]);
113
+ }
114
+ }
115
+ }
116
+
117
+ // Return the dotProduct of two sparse vectors
118
+ public int dotProduct (SparseVector vec ) {
119
+ int res = 0 ;
120
+ if (v. size() > vec. v. size()) {
121
+ Map<Integer , Integer > t = v;
122
+ v = vec. v;
123
+ vec. v = t;
124
+ }
125
+ for (Map . Entry<Integer , Integer > entry : v. entrySet()) {
126
+ int i = entry. getKey(), num = entry. getValue();
127
+ res += num * vec. v. getOrDefault(i, 0 );
128
+ }
129
+ return res;
130
+ }
131
+ }
132
+
133
+ // Your SparseVector object will be instantiated and called as such:
134
+ // SparseVector v1 = new SparseVector(nums1);
135
+ // SparseVector v2 = new SparseVector(nums2);
136
+ // int ans = v1.dotProduct(v2);
80
137
```
81
138
82
139
### ** ...**
0 commit comments