leetcode update

This commit is contained in:
gameloader 2024-03-10 12:27:56 +08:00
parent dd940b8a89
commit f159fc76cd

View File

@ -795,3 +795,85 @@ func getCommon(nums1 []int, nums2 []int) int {
### 总结
这是一道典型的双指针问题, 思路清晰就可以很快解决.
## day13 2024-03-10
### 349. Intersection of Two arrays
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
> Input: nums1 = [1,2,2,1], nums2 = [2,2]
> Output: [2]
Example 2:
> Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
> Output: [9,4]
> Explanation: [4,9] is also accepted.
### 题解
因为数组是无序数组, 寻找二者的相同元素比较困难, 故可先对两数组排序, 然后双指针遍历两个数组找到数组中的相同值. 将值作为key, key对应的value为true放入map中. 这里不需要多余判断map中是否已经存在这个key了, 因为再次给相同的key赋值不会增加新的条目, 而只是覆盖之前的key的值, 我们只需要key来判断map中是否有相同值.
### 代码
```go
func intersection(nums1 []int, nums2 []int) []int {
intersection := make(map[int]bool)
sort.Ints(nums1)
sort.Ints(nums2)
index1, index2 := 0,0
for index1 < len(nums1) && index2 < len(nums2){
if nums1[index1] < nums2[index2]{
index1++
}else if nums1[index1] > nums2[index2]{
index2++
}else{
_, ok := intersection[nums1[index1]]
if !ok{
intersection[nums1[index1]] = true
}
index1++
index2++
}
}
var result []int
for key, _ := range intersection{
result = append(result, key)
}
return result
}
```
### 总结
在查看他人题解过程中, 发现排序其实是没有必要的, 可以直接将一个数组中的值全部作为key, 对应的value为true放入map中. 然后遍历另外一个数组, 同时判断当前遍历的元素在不在map中, 若存在则将其放入结果数组中, 同时将map中key对应的value置为false, 表示该key已经被访问过, 这样可以避免在结果数组中添加重复元素.
一个示例代码如下
```go
func intersection(nums1 []int, nums2 []int) []int {
res := make([]int, 0)
m := make(map[int]bool, len(nums1))
for _, v := range nums1 {
if _, exists := m[v]; exists {
continue
}
m[v] = false
}
for _, v := range nums2 {
used, exists := m[v]
if exists && !used {
res = append(res, v)
m[v] = true
}
}
return res
}
```