[leetcode] The sum of four numbers, double pointer vs Hassi table

After doing the sum of three numbers, it is easy to do the sum of four numbers. Here, we mainly use double pointers to perform the sum of two numbers. The other two numbers use the enumeration method, and the complexity is O(n^3). code show as below:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []

        def helper(num,target):#三数之和
            result = []
            if len(num) < 3: #如果没有3个数
                return #爬
            for i in range(len(num)-2): #第二次枚举
                if i > 0 and num[i] == num[i-1]:#优化,防止枚举重复
                    continue
                left = i + 1 #双指针开始动了
                right = len(num) -1
                while left < right:
                    sum_3 = num[i] + num[left] + num[right]
                    if sum_3 == target:
                        result.append([num[i],num[left],num[right]])#将此时的数字放入三数之和的结果
                        left += 1
                        right -= 1
                    elif sum_3 > target:
                        right -= 1
                    elif sum_3 < target:
                        left += 1
            return result

        nums.sort()
        print(nums)
        res = []
        for i in range(len(nums)-3):#第一次枚举
            if i > 0 and nums[i] == nums[i-1]:#防止枚举重复
                continue
            new_target = target - nums[i]#剩下三个数此时的和是new_target
            #回到三数之和
            session = nums[i+1:]
            temp = helper(session,new_target)
            print([i,temp])
            if temp != []: #有结果返回
                for j in temp:
                    o = j+[nums[i]] #将此时返回的结果与nums[i]相加
                    if o not in res:#防止重复呢
                        res.append(j+[nums[i]])
        return res

Of course, the double pointer is very simple. After reading other people's code, I found that the complexity of the hash table can reach O(n^2).
The reason is that the complexity of enumerating two numbers and hashing the sum of the other two numbers is O(n^2), so the overall complexity is:
O(n^2), at the expense of space.

代码如下:
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        ans = []
        nums.sort()
        len_nums = len(nums)

        # hash后两个数的和,并保存索引
        table = {
    
    }
        for j in range(len_nums-1, 2, -1):
            if j < len_nums-1 and nums[j] == nums[j+1]:
                continue
            if 4 * nums[j] < target:
                break
            if nums[j] + 3*nums[0] > target:
                continue
            for i in range(j-1, 1, -1):
                if i < j-1 and nums[i] == nums[i+1]:
                    continue
                if nums[j] + 3*nums[i] < target:
                    break
                if nums[j] + nums[i] + 2*nums[0] > target:
                    continue
                table.setdefault(nums[i] + nums[j], []).append((i, j))

        # 枚举前两个数
        for i in range(len_nums-3):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            if nums[i] * 4 > target:
                break
            if nums[i] + 3 * nums[-1] < target:
                continue
            for j in range(i + 1, len_nums-2):
                if j > i + 1 and nums[j] == nums[j-1]:
                    continue
                if nums[i] + 3*nums[j] > target:
                    break
                if nums[i] + nums[j] + 2*nums[-1] < target:
                    continue
                for index, jndex in table.get(target - nums[i] - nums[j], []):
                    if j < index:
                        ans.append([nums[i], nums[j], nums[index], nums[jndex]])

        return ans

作者:loyx
链接:https://leetcode-cn.com/problems/4sum/solution/ha-xi-biao-de-on2he-on3fang-fa-by-loyx/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

It’s another day to expand my mind

Guess you like

Origin blog.csdn.net/Sgmple/article/details/111303880