golang leetcode349两个数组的交集 map 双指针+排序

两个数组的交集 leetcode349

使用map

由于golang中没有set,这里算是模拟的一种方式
当然这里也可以用数组来代替map

// 最简易的方式
func intersection(nums1 []int, nums2 []int) []int {
	table := make(map[int]int)

	result := []int{}

	for _, i2 := range nums1 {
		table[i2] = 1
	}
	for _, i2 := range nums2 {
		if table[i2] == 1 {
			table[i2] = 0
			result = append(result, i2)
		}

	}
	return result
}

排序+双指针

对数组进行排序后,就可以通过双指针的方式从小到大开始比较两个数组
以下两种方法都是采取的这个思路,只是循环的方式不同,复杂度相同

// 排序+双指针
func intersection(nums1 []int, nums2 []int) []int {
	index1, index2 := 0, 0

	sort.Ints(nums1)
	sort.Ints(nums2)

	L1 := len(nums1)
	L2 := len(nums2)

	result := []int{}

	for index1 < L1 {

		//当出现不是等于的情况时直接for循环
		for nums1[index1] < nums2[index2] {
			index1++
			if index1 >= L1 {
				return result
			}
		}

		for nums1[index1] > nums2[index2] {
			index2++
			if index2 >= L2 {
				return result
			}
		}

		if nums1[index1] == nums2[index2] {
			result = append(result, nums1[index1])
			for nums1[index1] == nums2[index2] {
				index2++
				if index2 >= L2 {
					return result
				}
			}
		}
	}
	return result

}

func intersection(nums1 []int, nums2 []int) (res []int) {
    sort.Ints(nums1)
    sort.Ints(nums2)
    for i, j := 0, 0; i < len(nums1) && j < len(nums2); {
        x, y := nums1[i], nums2[j]
        if x == y {
            if res == nil || x > res[len(res)-1] {
                res = append(res, x)
            }
            i++
            j++
        } else if x < y {
            i++
        } else {
            j++
        }
    }
    return
}

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值