leetcode 16. 3Sum Closest

题目链接:

https://leetcode.com/problems/3sum-closest/

input:

nums = [-1, 2, 1, -4],
target= 1

output:

2 即 (-1 + 2 + 1 = 2).

特殊情况:

  • 输入列表中包含重复值,如nums = [1,1,1,1]target= 0,output:3
  • 要找的是最接近的值,并不一定能找到target

解题思路

  • 使用宽度优先的算法,先计算两个数的和,在计算三个数的和,之后对三个数的和进行检查,找到最接近target的值返回。
  • 由于nums中会有重复值,所以不可直接去重。

code

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        two_map={}
        two_dump_map={}
        clean_two_map={}
        three_map={}
        three_dump_map={}
        num_size=len(nums)
        nums.sort()
        #print(num_size)
        # 计算两个数的和
        for i,n1 in enumerate(nums) :
            for j,n2 in enumerate(nums[i+1:]):
                val=n2+n1
                #去掉会发生重复的部分
#                 if val in two_dump_map:
#                     two_dump_map[val]+=1
#                     continue
#                 if val in two_map:
#                     del two_map[val]
#                     two_dump_map[val]=2
#                     continue
                two_map[val]=[i,i+j+1]
        print(two_map)
        print(two_dump_map)
        del two_dump_map
        max_val=target-nums[0]
        min_val=target+nums[-1]
        #去掉会越界的数
        for val in list(two_map.keys()):
            if min_val<= val <= max_val:
                clean_two_map[val]=two_map[val]
        #print(two_map)
        #print(clean_two_map)
        for i,n3 in enumerate(nums) :
            for val,l in two_map.items():
                if i not in l:
                    three_val=val+n3
                    #找到这个值
                    if three_val ==target:
                        return three_val
#                     if three_val in three_dump_map:
#                         three_dump_map[three_val]+=1
#                         continue
#                     if three_val in three_map:
#                         three_dump_map[three_val]=2
#                         continue
                    three_map[three_val]=[l[0],l[1],i]
        #print(three_map)
        #print(three_dump_map)
        #未找到这个值,找最接近的值
        min=sys.maxsize
        val=0
        #删除重复
#         for k,v in three_dump_map.items():
#             if v > 3:
#                 del three_map[k]
        #计算最接近的值
        for v in three_map.keys():
            if abs(v-target) < min:
                min=abs(v-target)
                val=v
        return val
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值