【LeetCode】【18.4sum】(python版)

Description:

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

有了前面3sum的经验,本题很容易联想到一种思路是:仍然固定一个数a,使用3sum的算法求 b + c + d = target - a。这样只需要在3sum算法基础上稍微修改,并在最外层加一个循环,时间复杂度为 O ( n 3 ) O(n^3) O(n3)

class Solution(object):
    def threeSum(self, nums, target):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        n = len(nums)
        for i in range(n-2):
            if i > 0 and nums[i] == nums[i-1]: continue
            low = i + 1
            high = n - 1
            while low < high:
                cursum = nums[low] + nums[high] + nums[i]
                if cursum == target:
                    res.append([nums[i], nums[low], nums[high]])
                    while low < high and nums[low] == nums[low+1]:
                        low = low + 1
                    while low < high and nums[high] == nums[high-1]:
                        high = high - 1
                    high = high - 1
                    low = low + 1
                elif cursum > target:
                    high = high - 1
                else:
                    low = low + 1
        return res


    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i in range(len(nums) - 3):
            if i > 0 and nums[i] == nums[i - 1]: continue
            curres = self.threeSum(nums[i+1:], target - nums[i])
            if len(curres) > 0:
                for curarr in curres:
                    curarr.append(nums[i])
                    res.append(curarr[:])
        return res

第二种思路是先将数组两两求和保存结果S,在求和结果基础上进行3Sum计算,即求解 S 1 + c + d = t a r g e t S_1+c+d=target S1+c+d=target。需要注意的是,保存求和结果时也一并保存两数下标,避免重复计算。

class Solution(object):
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        from collections import defaultdict
        numLen, res, two_sum= len(nums), set(), defaultdict(list)
        if numLen < 4: return []
        nums.sort()
        for p in range(numLen):
            for q in range(p + 1, numLen):
                two_sum[nums[p] + nums[q]].append((p, q))
        for i in range(numLen):
            for j in range(i + 1, numLen - 2):
                T = target - nums[i] - nums[j]
                if T in two_sum:
                    for k in two_sum[T]:
                        if k[0] > j: res.add((nums[i], nums[j], nums[k[0]], nums[k[1]]))
        return [list(i) for i in res]
### 回答1: LeetCode是一个优秀的在线编程平台,提供了丰富的算法和数据结构题目供程序员练习。其中的简单题大多可以用Python语言编写,下面为您提供几个常见题目的Python本答案。 1. 两数之和(Two Sum) 题目描述:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 Python本答案: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for i, x in enumerate(nums): if target - x in d: return [d[target - x], i] d[x] = i 2. 反转字符串(Reverse String) 题目描述:编写一个函数,其作用是将输入的字符串反转过来。 Python本答案: class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 3. 回文数字(Palindrome Number) 题目描述:判断一个整数是否是回文数,例如:121是回文数,-121不是回文数。 Python本答案: class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False if x == 0: return True str_x = str(x) left, right = 0, len(str_x) - 1 while left < right: if str_x[left] != str_x[right]: return False left += 1 right -= 1 return True 以上只是这几个简单题目的Python本答案,实际上LeetCode上还有很多其他编程语言编写的优秀答案,需要程序员们自己去探索和实践。 ### 回答2: Leetcode是一个流行的在线编程题库,提供了许多关于算法和数据结构的题目,难度从简单到困难不等。Python是一种易学易用的编程语言,备受程序员欢迎。因此,许多程序员使用Python来解决Leetcode的编程问题。下面我将提供一些Python本的Leetcode简单题的答案。 1. 两数之和 题目描述:给定一个整数数组和一个目标值,在数组中找到两个数之和等于目标值。 解题思路:使用哈希表来存储数组中每个元素的值和索引,然后遍历每个元素时,查找目标值减去当前元素的值是否在哈希表中,如果存在,返回两个值的索引。 Python代码: def twoSum(nums, target): hash_table = {} for i, num in enumerate(nums): complement = target - num if complement in hash_table: return hash_table[complement], i hash_table[num] = i nums = [2, 7, 11, 15] target = 9 print(twoSum(nums, target)) # Output: (0, 1) 2. 路径总和 题目描述:给定一棵二叉树和一个目标值,判断是否存在从根节点到叶节点的路径,使得路径上所有节点的值相加等于目标值。 解题思路:遍历二叉树的所有路径,判断路径上所有节点的值相加是否等于目标值。 Python代码: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def hasPathSum(root, sum): if not root: return False if not root.left and not root.right and root.val == sum: return True return hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val) root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) sum = 22 print(hasPathSum(root, sum)) # Output: True 3. 最大子序和 题目描述:给定一个整数数组,找到一个具有最大和的子数组,返回该子数组的和。 解题思路:使用动态规划,定义状态dp[i]表示以第i个数结尾的最大子数组和,则状态转移方程为dp[i] = max(dp[i-1] + nums[i], nums[i])。 Python代码: def maxSubArray(nums): if not nums: return 0 n = len(nums) dp = [0] * n dp[0] = nums[0] for i in range(1, n): dp[i] = max(dp[i-1] + nums[i], nums[i]) return max(dp) nums = [-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(nums)) # Output: 6 总结:以上是三个Python本的Leetcode简单题的答案,它们涉及到哈希表、二叉树、动态规划等算法和数据结构。这些题目既考验了程序员的基本功,又是训练算法思维的好工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值