62
62
63
63
<!-- solution:start -->
64
64
65
- ### 方法一
65
+ ### 方法一:哈希表
66
+
67
+ 我们可以用一个哈希表 $\text{cnt}$ 统计数组 $\text{nums1}$ 中每个元素出现的次数,然后遍历数组 $\text{nums2}$,如果元素 $x$ 在 $\text{cnt}$ 中,并且 $x$ 的出现次数大于 $0$,那么将 $x$ 加入答案,然后将 $x$ 的出现次数减一。
68
+
69
+ 遍历结束后,返回答案数组即可。
70
+
71
+ 时间复杂度 $O(m + n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是数组 $\text{nums1}$ 和 $\text{nums2}$ 的长度。
66
72
67
73
<!-- tabs:start -->
68
74
@@ -71,36 +77,31 @@ tags:
71
77
``` python
72
78
class Solution :
73
79
def intersect (self , nums1 : List[int ], nums2 : List[int ]) -> List[int ]:
74
- counter = Counter(nums1)
75
- res = []
76
- for num in nums2:
77
- if counter[num] > 0 :
78
- res .append(num )
79
- counter[num ] -= 1
80
- return res
80
+ cnt = Counter(nums1)
81
+ ans = []
82
+ for x in nums2:
83
+ if cnt[x] :
84
+ ans .append(x )
85
+ cnt[x ] -= 1
86
+ return ans
81
87
```
82
88
83
89
#### Java
84
90
85
91
``` java
86
92
class Solution {
87
93
public int [] intersect (int [] nums1 , int [] nums2 ) {
88
- Map< Integer , Integer > counter = new HashMap<> () ;
89
- for (int num : nums1) {
90
- counter . put(num, counter . getOrDefault(num, 0 ) + 1 ) ;
94
+ int [] cnt = new int [ 1001 ] ;
95
+ for (int x : nums1) {
96
+ ++ cnt[x] ;
91
97
}
92
- List<Integer > t = new ArrayList<> ();
93
- for (int num : nums2) {
94
- if (counter. getOrDefault(num, 0 ) > 0 ) {
95
- t. add(num);
96
- counter. put(num, counter. get(num) - 1 );
98
+ List<Integer > ans = new ArrayList<> ();
99
+ for (int x : nums2) {
100
+ if (cnt[x]-- > 0 ) {
101
+ ans. add(x);
97
102
}
98
103
}
99
- int [] res = new int [t. size()];
100
- for (int i = 0 ; i < res. length; ++ i) {
101
- res[i] = t. get(i);
102
- }
103
- return res;
104
+ return ans. stream(). mapToInt(Integer :: intValue). toArray();
104
105
}
105
106
}
106
107
```
@@ -111,78 +112,78 @@ class Solution {
111
112
class Solution {
112
113
public:
113
114
vector<int > intersect(vector<int >& nums1, vector<int >& nums2) {
114
- unordered_map<int, int> counter;
115
- for (int num : nums1) ++counter[ num] ;
116
- vector<int > res;
117
- for (int num : nums2) {
118
- if (counter[ num] > 0) {
119
- --counter[ num] ;
120
- res.push_back(num);
115
+ unordered_map<int, int> cnt;
116
+ for (int x : nums1) {
117
+ ++cnt[ x] ;
118
+ }
119
+ vector<int > ans;
120
+ for (int x : nums2) {
121
+ if (cnt[ x] -- > 0) {
122
+ ans.push_back(x);
121
123
}
122
124
}
123
- return res ;
125
+ return ans ;
124
126
}
125
127
};
126
128
```
127
129
128
130
#### Go
129
131
130
132
```go
131
- func intersect(nums1 []int, nums2 []int) []int {
132
- counter := make( map[int]int)
133
- for _, num := range nums1 {
134
- counter[num ]++
133
+ func intersect(nums1 []int, nums2 []int) (ans []int) {
134
+ cnt := map[int]int{}
135
+ for _, x := range nums1 {
136
+ cnt[x ]++
135
137
}
136
- var res []int
137
- for _, num := range nums2 {
138
- if counter[num] > 0 {
139
- counter[num]--
140
- res = append(res, num)
138
+ for _, x := range nums2 {
139
+ if cnt[x] > 0 {
140
+ ans = append(ans, x)
141
+ cnt[x]--
141
142
}
142
143
}
143
- return res
144
+ return
144
145
}
145
146
```
146
147
147
148
#### TypeScript
148
149
149
150
``` ts
150
151
function intersect(nums1 : number [], nums2 : number []): number [] {
151
- const map = new Map <number , number >() ;
152
- for (const num of nums1 ) {
153
- map . set ( num , ( map . get ( num ) ?? 0 ) + 1 ) ;
152
+ const cnt : Record <number , number > = {} ;
153
+ for (const x of nums1 ) {
154
+ cnt [ x ] = ( cnt [ x ] || 0 ) + 1 ;
154
155
}
155
-
156
- const res = [];
157
- for (const num of nums2 ) {
158
- if (map .has (num ) && map .get (num ) !== 0 ) {
159
- res .push (num );
160
- map .set (num , map .get (num ) - 1 );
156
+ const ans: number [] = [];
157
+ for (const x of nums2 ) {
158
+ if (cnt [x ]-- > 0 ) {
159
+ ans .push (x );
161
160
}
162
161
}
163
- return res ;
162
+ return ans ;
164
163
}
165
164
```
166
165
167
166
#### Rust
168
167
169
168
``` rust
170
169
use std :: collections :: HashMap ;
170
+
171
171
impl Solution {
172
172
pub fn intersect (nums1 : Vec <i32 >, nums2 : Vec <i32 >) -> Vec <i32 > {
173
- let mut map = HashMap :: new ();
174
- for num in nums1 . iter () {
175
- * map . entry (num ). or_insert (0 ) += 1 ;
173
+ let mut cnt = HashMap :: new ();
174
+ for & x in & nums1 {
175
+ * cnt . entry (x ). or_insert (0 ) += 1 ;
176
176
}
177
-
178
- let mut res = vec! [];
179
- for num in nums2 . iter () {
180
- if map . contains_key (num ) && map . get (num ). unwrap () != & 0 {
181
- map . insert (num , map . get (& num ). unwrap () - 1 );
182
- res . push (* num );
177
+ let mut ans = Vec :: new ();
178
+ for & x in & nums2 {
179
+ if let Some (count ) = cnt . get_mut (& x ) {
180
+ if * count > 0 {
181
+ ans . push (x );
182
+ * count -= 1 ;
183
+ }
183
184
}
184
185
}
185
- res
186
+ ans
186
187
}
187
188
}
188
189
```
@@ -196,18 +197,17 @@ impl Solution {
196
197
* @return {number[]}
197
198
*/
198
199
var intersect = function (nums1 , nums2 ) {
199
- const counter = {};
200
- for (const num of nums1) {
201
- counter[num ] = (counter[num ] || 0 ) + 1 ;
200
+ const cnt = {};
201
+ for (const x of nums1) {
202
+ cnt[x ] = (cnt[x ] || 0 ) + 1 ;
202
203
}
203
- let res = [];
204
- for (const num of nums2) {
205
- if (counter[num] > 0 ) {
206
- res .push (num);
207
- counter[num] -= 1 ;
204
+ const ans = [];
205
+ for (const x of nums2) {
206
+ if (cnt[x]-- > 0 ) {
207
+ ans .push (x);
208
208
}
209
209
}
210
- return res ;
210
+ return ans ;
211
211
};
212
212
```
213
213
@@ -216,30 +216,22 @@ var intersect = function (nums1, nums2) {
216
216
``` cs
217
217
public class Solution {
218
218
public int [] Intersect (int [] nums1 , int [] nums2 ) {
219
- HashSet < int > hs1 = new HashSet <int >(nums1 .Concat (nums2 ).ToArray ());
220
- Dictionary < int , int > dict = new Dictionary <int , int >();
221
- List < int > result = new List <int >();
222
-
223
- foreach (int x in hs1 ) {
224
- dict [x ] = 0 ;
225
- }
226
-
219
+ Dictionary < int , int > cnt = new Dictionary <int , int >();
227
220
foreach (int x in nums1 ) {
228
- if (dict .ContainsKey (x )) {
229
- dict [x ] += 1 ;
221
+ if (cnt .ContainsKey (x )) {
222
+ cnt [x ]++ ;
230
223
} else {
231
- dict [x ] = 1 ;
224
+ cnt [x ] = 1 ;
232
225
}
233
226
}
234
-
227
+ List < int > ans = new List < int >();
235
228
foreach (int x in nums2 ) {
236
- if (dict [x ] > 0 ) {
237
- result .Add (x );
238
- dict [x ] -= 1 ;
229
+ if (cnt . ContainsKey ( x ) && cnt [x ] > 0 ) {
230
+ ans .Add (x );
231
+ cnt [x ]-- ;
239
232
}
240
233
}
241
-
242
- return result .ToArray ();
234
+ return ans .ToArray ();
243
235
}
244
236
}
245
237
```
@@ -254,17 +246,24 @@ class Solution {
254
246
* @return Integer[]
255
247
*/
256
248
function intersect($nums1, $nums2) {
257
- $rs = [];
258
- for ($i = 0; $i < count($nums1); $i++) {
259
- $hashtable[$nums1[$i]] += 1;
249
+ $cnt = [];
250
+ foreach ($nums1 as $x) {
251
+ if (isset($cnt[$x])) {
252
+ $cnt[$x]++;
253
+ } else {
254
+ $cnt[$x] = 1;
255
+ }
260
256
}
261
- for ($j = 0; $j < count($nums2); $j++) {
262
- if (isset($hashtable[$nums2[$j]]) && $hashtable[$nums2[$j]] > 0) {
263
- array_push($rs, $nums2[$j]);
264
- $hashtable[$nums2[$j]] -= 1;
257
+
258
+ $ans = [];
259
+ foreach ($nums2 as $x) {
260
+ if (isset($cnt[$x]) && $cnt[$x] > 0) {
261
+ $ans[] = $x;
262
+ $cnt[$x]--;
265
263
}
266
264
}
267
- return $rs;
265
+
266
+ return $ans;
268
267
}
269
268
}
270
269
```
0 commit comments