File tree Expand file tree Collapse file tree 2 files changed +65
-1
lines changed Expand file tree Collapse file tree 2 files changed +65
-1
lines changed Original file line number Diff line number Diff line change 8
8
| 9| [ 回文数] ( https://leetcode-cn.com/problems/palindrome-number/ ) | [ JavaScript] ( ./algorithms/palindrome-number.js ) | Easy|
9
9
| 14| [ 最长公共前缀] ( https://leetcode-cn.com/problems/longest-common-prefix/ ) | [ JavaScript] ( ./algorithms/longest-common-prefix.js ) | Easy|
10
10
| 21| [ 合并两个有序链表] ( https://leetcode-cn.com/problems/merge-two-sorted-lists/ ) | [ JavaScript] ( ./algorithms/merge-two-sorted-lists.js ) | Easy|
11
- | 189| [ 轮转数组] ( https://leetcode-cn.com/problems/rotate-array/ ) | [ JavaScript] ( ./algorithms/rotate-array.js ) | Medium|
11
+ | 189| [ 轮转数组] ( https://leetcode-cn.com/problems/rotate-array/ ) | [ JavaScript] ( ./algorithms/rotate-array.js ) | Medium|
12
+ | 349| [ 两个数组的交集] ( https://leetcode-cn.com/problems/intersection-of-two-arrays/ ) | [ JavaScript] ( ./algorithms/intersection-of-two-arrays.js ) | Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums1
3
+ * @param {number[] } nums2
4
+ * @return {number[] }
5
+ */
6
+
7
+ // 方法一:映射(降低时间复杂度)
8
+ var intersection = function ( nums1 , nums2 ) {
9
+ const result = [ ] ;
10
+ const nums2Obj = { } ;
11
+ // 保存出现过的值
12
+ const occured = { } ;
13
+
14
+ for ( let i = 0 ; i < nums2 . length ; i ++ ) {
15
+ nums2Obj [ nums2 [ i ] ] = true ;
16
+ }
17
+
18
+ for ( let i = 0 ; i < nums1 . length ; i ++ ) {
19
+ const curr = nums1 [ i ] ;
20
+
21
+ if ( nums2Obj [ curr ] && ! occured [ curr ] ) {
22
+ occured [ curr ] = true ;
23
+
24
+ result . push ( nums1 [ i ] ) ;
25
+ }
26
+ }
27
+
28
+ return result ;
29
+ } ;
30
+
31
+ // 方法二:排序 + 双指针
32
+ var intersection = function ( nums1 , nums2 ) {
33
+ nums1 . sort ( ( a , b ) => a - b ) ;
34
+ nums2 . sort ( ( a , b ) => a - b ) ;
35
+
36
+ let len1 = nums1 . length ;
37
+ let len2 = nums2 . length ;
38
+ let l1 , l2 , result = [ ] ;
39
+ l1 = l2 = 0 ;
40
+
41
+ // 上一次出现相等的数字
42
+ let lastEqualNumber ;
43
+
44
+ while ( l1 < len1 && l2 < len2 ) {
45
+ if ( nums1 [ l1 ] < nums2 [ l2 ] ) {
46
+ l1 ++ ;
47
+ } else if ( nums1 [ l1 ] > nums2 [ l2 ] ) {
48
+ l2 ++ ;
49
+ } else {
50
+ const curr = nums1 [ l1 ] ;
51
+
52
+ if ( curr !== lastEqualNumber ) {
53
+ result . push ( curr ) ;
54
+ }
55
+
56
+ lastEqualNumber = curr ;
57
+ l1 ++ ;
58
+ l2 ++ ;
59
+ }
60
+ }
61
+
62
+ return result ;
63
+ } ;
You can’t perform that action at this time.
0 commit comments