diff --git a/Algorithms/349. Intersection of Two Arrays/349. Intersection of Two Arrays.go b/Algorithms/349. Intersection of Two Arrays/349. Intersection of Two Arrays.go new file mode 100644 index 00000000..2deac4a4 --- /dev/null +++ b/Algorithms/349. Intersection of Two Arrays/349. Intersection of Two Arrays.go @@ -0,0 +1,16 @@ +package leetcode + +func intersection(nums1 []int, nums2 []int) []int { + m := map[int]bool{} + var res []int + for _, n := range nums1 { + m[n] = true + } + for _, n := range nums2 { + if m[n] { + delete(m, n) + res = append(res, n) + } + } + return res +} diff --git a/Algorithms/349. Intersection of Two Arrays/349. Intersection of Two Arrays_test.go b/Algorithms/349. Intersection of Two Arrays/349. Intersection of Two Arrays_test.go new file mode 100644 index 00000000..b17d4b5b --- /dev/null +++ b/Algorithms/349. Intersection of Two Arrays/349. Intersection of Two Arrays_test.go @@ -0,0 +1,69 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +type question349 struct { + para349 + ans349 +} + +// para 是参数 +// one 代表第一个参数 +type para349 struct { + one []int + another []int +} + +// ans 是答案 +// one 代表第一个答案 +type ans349 struct { + one []int +} + +func Test_Problem349(t *testing.T) { + + qs := []question349{ + + question349{ + para349{[]int{}, []int{}}, + ans349{[]int{}}, + }, + + question349{ + para349{[]int{1}, []int{1}}, + ans349{[]int{1}}, + }, + + question349{ + para349{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}}, + ans349{[]int{1, 2, 3, 4}}, + }, + + question349{ + para349{[]int{1, 2, 2, 1}, []int{2, 2}}, + ans349{[]int{2}}, + }, + + question349{ + para349{[]int{1}, []int{9, 9, 9, 9, 9}}, + ans349{[]int{}}, + }, + + question349{ + para349{[]int{4, 9, 5}, []int{9, 4, 9, 8, 4}}, + ans349{[]int{9, 4}}, + }, + // 如需多个测试,可以复制上方元素。 + } + + fmt.Printf("------------------------Leetcode Problem 349------------------------\n") + + for _, q := range qs { + _, p := q.ans349, q.para349 + fmt.Printf("【input】:%v 【output】:%v\n", p, intersection(p.one, p.another)) + } + fmt.Printf("\n\n\n") +} diff --git a/Algorithms/349. Intersection of Two Arrays/README.md b/Algorithms/349. Intersection of Two Arrays/README.md new file mode 100644 index 00000000..142d4744 --- /dev/null +++ b/Algorithms/349. Intersection of Two Arrays/README.md @@ -0,0 +1,31 @@ +# [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) + +## 题目 + +Given two arrays, write a function to compute their intersection. + + +Example 1: + +```c +Input: nums1 = [1,2,2,1], nums2 = [2,2] +Output: [2] +``` + +Example 2: + +```c +Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] +Output: [9,4] +``` + +Note: + +- Each element in the result must be unique. +- The result can be in any order. + +## 题目大意 + +找到两个数组的交集元素,如果交集元素同一个数字出现了多次,只输出一次。 + +把数组一的每个数字都存进字典中,然后在数组二中依次判断字典中是否存在,如果存在,在字典中删除它(因为输出要求只输出一次)。 \ No newline at end of file