LeetCode 答案(python)18-24
18.四个数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
N = len(nums)
if N < 4:
return result
nums = sorted(nums)
for i in range(N - 3):
if sum(nums[i:i + 4]) > target or sum(nums[-4:]) < target:
break
if nums[i] + sum(nums[-3:]) < target:
continue
if i > 0 and nums[i] == nums[i - 1]:
continue
target2 = target - nums[i]
for j in range(i + 1, N - 2):
if sum(nums[j:j + 3]) > target2 or sum(nums[-3:]) < target2:
break
if nums[j] + sum(nums[-2:]) < target2:
continue
if j > i + 1 and nums[j] == nums[j - 1]:
continue
target3 = target2 - nums[j]
left = j + 1
right = N - 1
while (left < right):
if nums[left] + nums[right] == target3:
result.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 nums[left] + nums[right] < target3:
left += 1
else:
right -= 1
return result
19 删除链表中倒数第n个节点
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: Li
"""
dao_n, first = head
for i in range(n):
first = first.next
if not first:
return dao_n.next
while first:
dao_n = dao_n.next
first = first.next
dao_n.next = dao_n.next.next
return head
20 有效括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
dict = {"]": "[", "}": "{", ")": "("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
21合并两个有序链表
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dumy = ListNode(0)
cur = dumy
while l1 or l2:
if l1 and l2:
if l1.val > l2.val:
cur.next = l2
l2 = l2.next
else:
cur.next = l1
l1 = l1.next
elif l1:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
return dumy.next
22 括号生成
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]22
"""
if n == 0:
return []
left = right = n
result = []
self.generate(left, right, result, '')
return result
def generate(self, left, right, result, string):
if left == 0 and right == 0:
result.append(string)
return
if left:
self.generate(left - 1, right , result, string+'(')
if left < right:
self.generate(left, right - 1, result, string+')') a = Solution()
print(a.generateParenthesis(4))
23合并K个排序链表
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists):
pre = cur = ListNode(0) heap = []
for i in range(len(lists)):
if lists[i]:
heapq.heappush(heap, (lists[i].val, i, lists[i])) while heap:
node = heapq.heappop(heap)
idx = node[1]
cur.next = node[2]
cur = cur.nextb if cur.next:
heapq.heappush(heap, (cur.next.val, idx, cur.next)) return pre.next
LeetCode 答案(python)18-24的更多相关文章
- 2016年10月13日 星期四 --出埃及记 Exodus 18:24
2016年10月13日 星期四 --出埃及记 Exodus 18:24 Moses listened to his father-in-law and did everything he said.于 ...
- LeetCode专题-Python实现之第28题: Implement strStr()
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第27题:Remove Element
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第21题:Merge Two Sorted Lists
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第20题:Valid Parentheses
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第9题:Palindrome Number
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第14题:Longest Common Prefix
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第13题:Roman to Integer
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第7题:Reverse Integer
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
随机推荐
- ImportError: No module named rospy
Traceback (most recent call last): File "manage.py", line 4, in <module> import rosp ...
- ZR#996
ZR#996 解法: 若删除长度为 $ x $ 的子串后序列中没有相同元素,那么一定有至少一个长度为 $ x+1 $ 的子串,删除它后序列中也没有相同元素. CODE: #include <io ...
- ASP.NET的MVC设计模式
当开发者听到“设计模式”这个词时,他们通常联想到两个场景.一组开发者正在讨论许多创造性意见,正在开会,但是却没有进行编码.另外一组人能制定出正确的计划,保证系统能够开发成功,代码可以重用. 而现实一般 ...
- Leetcode题目300.最长上升子序列(动态规划-中等)
题目描述: 给定一个无序的整数数组,找到其中最长上升子序列的长度. 示例: 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度 ...
- vue-cli项目模板的一些思考
之前有个想法,就是要利用vue写一套ui.然后当时也没有搞清楚到底怎么写. 几经周转吧,通过付费的方式在gitbook上面找到了答案. 找到答案之后再看我们正在开发的项目,看伙伴写的代码,突然发现完全 ...
- Flask 静态文件缓存问题
大家好,今天才发现很多学习Flask的小伙伴都有这么一个问题,清理缓存好麻烦啊,今天就教大家怎么解决. 大家在使用Flask静态文件的时候,每次更新,发现CSS或是Js或者其他的文件不会更新. 这是因 ...
- [maven]maven插件 tomcat7-maven-plugin 的使用
使用 tomcat7-maven-plugin,可以将tomcat内嵌到web项目中,直接运行webapp项目. 第一步.pom.xml的配置: <build> <plugins&g ...
- TensorFlow Object Detection API —— 制作自己的模型
https://blog.csdn.net/qq_24474463/article/details/81530900 (t20190518) luo@luo-All-Series:~/MyFile/T ...
- 阶段5 3.微服务项目【学成在线】_day04 页面静态化_22-页面静态化-静态化测试-静态化程序测试
测试service内些的静态化的方法 先新建一个测试类 模板的id 放到下拉的静态数据里面 这样这条数据 就是用用的轮播图005这个模板 把这条数据静态化 进入到断点里面.先获取数据模型 获取模板时 ...
- pip使用笔记
例子: pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -U funcat -i: 指定库的安装源 -U:升级 原来已经安装的包,不带U ...