leetcode: 18. 4Sum
来源:互联网 发布:希拉里为什么落选知乎 编辑:程序博客网 时间:2024/06/02 05:38
Problem
# Given an array S of n integers, are there elements a, b, c, and d in S 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.## For example, given array S = [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]# ]
AC
# TODO: Cannot ac in python3, but pass in python2class Solution(): def fourSum(self, x, target): x.sort() res = [] for i in range(len(x) - 3): if i == 0 or x[i] != x[i - 1]: for j in range(i + 1, len(x) - 2): if j == i + 1 or x[j] != x[j - 1]: mid, right = j + 1, len(x) - 1 while mid < right: dis = (x[i] + x[j] + x[mid] + x[right]) - target if dis == 0: res.append([x[i], x[j], x[mid], x[right]]) mid, right = mid + 1, right - 1 while mid < right and x[mid] == x[mid - 1]: mid += 1 while mid < right and x[right] == x[right + 1]: right -= 1 elif dis < 0: mid += 1 else: right -= 1 return resif __name__ == '__main__': assert Solution().fourSum([1, 0, -1, 0, -2, 2], 0) == [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
阅读全文
2 0
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum LeetCode
- leetcode 18. 4Sum
- 【LeetCode】18. 4Sum
- LeetCode - 18. 4Sum
- leetcode 18. 4Sum
- Leetcode 18. 4Sum
- LeetCode 18. 4Sum
- 【leetcode】18. 4Sum
- leetcode 18. 4Sum
- [leetcode]18. 4Sum
- leetcode 18. 4Sum
- leetcode 18. 4Sum
- leetcode 18. 4Sum
- [LeetCode] 18. 4Sum
- LeetCode 18. 4Sum
- shell学习十七--条件表达式test、[]、[[]]
- 171107 逆向-SWPU(Re300-解密)
- 深入理解机器学习:从理论到算法-习题全解之第十七章:多分类、排序与复杂预测
- gcc--编译
- Robot Framework-工具简介及入门使用
- leetcode: 18. 4Sum
- 数据结构与算法视频推荐
- Robot Framework-DatabaseLibrary数据库(MySql)
- 深入理解机器学习:从理论到算法-习题全解之第十八章:决策树
- [Lintcode] #153 数字组合 II
- 函数调用堆栈
- springboot jar jsp
- 利用Sulley测试easyftp服务器
- 深入理解机器学习:从理论到算法-习题全解之第十九章:最近邻