LeetCode021:最接近的三数之和
Given an array nums of n integers and an integer target,
find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
这一题和15题三数之和为0解题思路类似。解决方案出自LeetCode-python 16.最接近的三数之和。
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
l, r = i+1, len(nums)-1
while l<r:
sum = nums[i] + nums[l] + nums[r]
if sum == target:
return sum
if abs(res-target)>abs(sum-target):
res = sum
if sum<target:
l += 1
else:
r -= 1
return res
LeetCode021:有效的括号
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
解决方案出自LeetCode-python 20.有效的括号。这一题的核心解决思路就是用一个字典存放成对的括号,key放左括号,value放右括号。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dic ={ '(':')', '[':']', '{':'}'}
stack = []
for c in s:
if c in dic:
stack.append(c)
else:
if stack:
top = stack.pop()
if c != dic[top]:
return False
else:
return False
return not stack
LeetCode021:合并两个有序链表
Merge two sorted linked lists and return it as a sorted list.
The list should be made by splicing together the nodes of the first two lists.
看到一个代码比较简单的解法LeetCode中文版解决方案那里4行python那个解答,利用到了递归思想,但是。。。这个代码没看明白=_=
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val > l2.val: l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
作者:QQqun902025048
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/python-4xing-by-knifezhu-3/
来源:力扣(LeetCode)
还有一个比较便于理解的递归解法:
https://github.com/liutao9/LeetCode/blob/master/001_050/021%20%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8.md。这个人提供了两个解决方案,每个方案提供了java, c++, python三种语言实现。
def mergeTwoLists(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
任务链接:
team-learning-program/LeetCodeTencent/016 最接近的三数之和.md
team-learning-program/LeetCodeTencent/020 有效的括号.md
team-learning-program/LeetCodeTencent/021 合并两个有序链表.md