添加 problem 350

This commit is contained in:
YDZ
2019-06-06 08:39:35 +08:00
parent 6885fbfa92
commit d64e27bf62
3 changed files with 132 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
package leetcode
func intersect(nums1 []int, nums2 []int) []int {
m := map[int]int{}
var res []int
for _, n := range nums1 {
m[n]++
}
for _, n := range nums2 {
if m[n] > 0 {
res = append(res, n)
m[n]--
}
}
return res
}

View File

@@ -0,0 +1,74 @@
package leetcode
import (
"fmt"
"testing"
)
type question350 struct {
para350
ans350
}
// para 是参数
// one 代表第一个参数
type para350 struct {
one []int
another []int
}
// ans 是答案
// one 代表第一个答案
type ans350 struct {
one []int
}
func Test_Problem350(t *testing.T) {
qs := []question350{
question350{
para350{[]int{}, []int{}},
ans350{[]int{}},
},
question350{
para350{[]int{1}, []int{1}},
ans350{[]int{1}},
},
question350{
para350{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}},
ans350{[]int{1, 2, 3, 4}},
},
question350{
para350{[]int{1, 2, 2, 1}, []int{2, 2}},
ans350{[]int{2, 2}},
},
question350{
para350{[]int{1}, []int{9, 9, 9, 9, 9}},
ans350{[]int{}},
},
question350{
para350{[]int{4, 9, 5}, []int{9, 4, 9, 8, 4}},
ans350{[]int{9, 4}},
},
question350{
para350{[]int{4, 9, 5, 9, 4}, []int{9, 4, 9, 8, 4, 7, 9, 4, 4, 9}},
ans350{[]int{9, 4, 9, 4}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 350------------------------\n")
for _, q := range qs {
_, p := q.ans350, q.para350
fmt.Printf("【input】:%v 【output】:%v\n", p, intersect(p.one, p.another))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,42 @@
# [350. Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)
## 题目
Given two arrays, write a function to compute their intersection.
Example 1:
```c
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
```
Example 2:
```c
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
```
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
## 题目大意
这题是第 349 题的加强版。要求输出 2 个数组的交集元素,如果元素出现多次,要输出多次。
这一题还是延续第 349 题的思路。把数组一中的数字都放进字典中,另外字典的 key 是数组中的数字value 是这个数字出现的次数。在扫描数组二的时候,每取出一个存在的数组,把字典中的 value 减一。如果 value 是 0 代表不存在这个数字。