提交 c27bd5d8 编写于 作者: 檀越@新空间's avatar 檀越@新空间 🐭

fix:四数之和

上级 8600ec46
"""
四数之和
"""
from typing import List
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
"""
四数之和 转化为三数之和,理清楚第一个数和第二个之间的关系
:param nums:
:param target:
:return:
"""
nums.sort()
res = []
n = len(nums)
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1, n - 1
while left < right:
s = nums[i] + nums[j] + nums[left] + nums[right]
if s == target:
res.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif s > target:
right -= 1
else:
left += 1
return res
if __name__ == '__main__':
result = Solution().fourSum([1, 0, -1, 0, -2, 2], 0)
print(result)
"""
在二叉树中分配硬币
"""
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def distributeCoins(self, root: Optional[TreeNode]) -> int:
pass
if __name__ == '__main__':
result = Solution().distributeCoins(3, 0, 0)
print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册