LeetCode Practice Journal | Day4_哈希表(go)

LeetCode Practice Journal | Day4_哈希表(go)

7、leetcode454 四数相加

四数相加

func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
    m:=make(map[int]int)
    count:=0
    for _,v1:=range nums1{
        for _,v2:=range nums2{
            m[v1+v2]++
        }
    }
    for _,v3:=range nums3{
        for _,v4:=range nums4{
            sum := -v3-v4
            if countval,ok:=m[sum];ok{
                count+=countval
            }
        }
    }
    return count
}

leetcode15 三数之和

func threeSum(nums []int) [][]int {
    len:=len(nums)
    sort.Ints(nums)
    ans := make([][]int,0)

    for first:=0;first<len;first++{
        if first>0&&nums[first] ==nums[first-1]{
            continue
        }
        third := len-1
        target := -1*nums[first]
        if first<=len-3{
            s := nums[first]+nums[first+1]+nums[first+2]
        if s>0{
            break
        }
        s2:=nums[first]+nums[len-2]+nums[len-1]
        if s2<0{
            continue
        }
        }
        for second := first+1;second<len;second++{
            if second>first+1&&nums[second]==nums[second-1]{
                continue
            }
            for second<third&&nums[second]+nums[third]>target{
                third--
            }
            if second==third{
                break
            }
            if nums[second]+nums[third] ==target{
                ans = append(ans,[]int{nums[first],nums[second],nums[third]})
            }
        }

    }
    return ans
}

leetcode18 四数之和

func fourSum(nums []int, target int) [][]int {
    if len(nums)<4{
        return nil
    }
    sort.Ints(nums)
    var res[][]int
    for i:=0;i<len(nums)-3;i++{
        n1 := nums[i]
        if i>0&&n1 ==nums[i-1]{
            continue
        }
        for j:=i+1;j<len(nums)-2;j++{
            n2 :=nums[j]
            if j>i+1&&n2==nums[j-1]{
                continue
            }
            l :=j+1
            r:=len(nums)-1
            for l<r{
                n3 :=nums[l]
                n4 := nums[r]
                sum :=n1+n2+n3+n4
                if sum<target{
                    l++
                }else if sum>target{
                    r--
                }else{
                    res=append(res,[]int{n1,n2,n3,n4})
                    for l<r&&n3 ==nums[l+1]{
                        l++
                    }
                    for l<r&&n4 ==nums[r-1]{
                        r--
                    }
                    r--
                    l++
                }
            }
        }
    }
    return res
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值