Skip to content

Commit 9b58414

Browse files
author
yangguang_chen
committed
* intersection of two array
1 parent ca07375 commit 9b58414

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
- [198.house-robber](./src/198-HouseRobber/house_robber.go)
1414
- [231.power-of-two](./src/231-PowerOfTwo/power_of2.go)
1515
- [290.word-pattern](./src/290-WordPattern/word_pattern.go)
16+
- [349.intersection-of-two-array](./src/349-IntersectionOf2Array/inter_of2.go)
1617
- [367.valid-perfect-square](./src/367-ValidPerfectSquare/367-valid-perfect-square.go)
1718
- [704.binary-search](./src/704-BinarySearch/704-binary-search.go)
1819

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Given two arrays, write a function to compute their intersection.
2+
// Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
3+
// Note:
4+
// Each element in the result must be unique.
5+
// The result can be in any order.
6+
7+
package inof2arr
8+
9+
import (
10+
"strconv"
11+
)
12+
13+
func IntersectionOf2Array(iarr1, iarr2 []int) []int {
14+
var ret []int
15+
len1 := len(iarr1)
16+
len2 := len(iarr2)
17+
18+
var maxLen, minLen int
19+
if len1 > len2 {
20+
maxLen = len1
21+
minLen = len2
22+
} else {
23+
maxLen = len2
24+
maxLen = len1
25+
}
26+
27+
m := make(map[string]int)
28+
for i := 0; i < maxLen; i++ {
29+
for j := 0; j < minLen; j++ {
30+
if iarr1[i] != iarr2[j] {
31+
continue
32+
}
33+
k := strconv.Itoa(i)
34+
m[k] = iarr1[i]
35+
if _, ok := m[k]; !ok {
36+
ret = append(ret, iarr1[i])
37+
}
38+
}
39+
}
40+
return ret
41+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package inof2arr
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestIntersectionOf2Array(t *testing.T) {
8+
arr_1 := []int{1, 1, 2, 2}
9+
arr_2 := []int{2, 2}
10+
11+
res := IntersectionOf2Array(arr_1, arr_2)
12+
for _, v := range res {
13+
if v == 2 {
14+
t.Log("arr_1:", arr_1, " and arr_2:", arr_2, " have intersection partition")
15+
break
16+
}
17+
t.Error("arr_1:", arr_1, " and arr_2:", arr_2, " have no intersection partition")
18+
}
19+
}

0 commit comments

Comments
 (0)