LeetCode[Array]---- 4Sum
来源:互联网 发布:易语言统计成绩源码 编辑:程序博客网 时间:2024/04/18 17:45
4Sum
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
分析:
是3Sum这类题目的升级版。题目要求给定一个数组nums,从中找到所有的不重复的四个元素a,b,c,d,使得a + b + c + d的和等于target。
依旧是借助3Sum题目的思路。依旧是对数组进行排序,然后使用双指针进行遍历,不一样的是,对于四个元素的情况,需要在三个元素的情况之上多一层循环。
具体的,我们把排序好的数组分成三个不相交部分P1, P2,P3,从P1中选择一个元素a,从P2中选择另一个元素b,然后使用双指针由前往后和由后往前的选择元素c和d,如果a + b + c + d的和nsum等于target,则记录此时的abcd;如果nsum大于target,则右指针向左移动,减少nsum值;如果nsum小于target,那么左指针向右移动,增加nsum值。
另外,对于所有的解需要进行去重。具体可以判断每次选择的元素是否与前一次选择的元素相同,如果相同则跳过不选。
相应的代码为:
class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ nums.sort() nums_len = len(nums) res = [] for i in range(nums_len - 3): if i and nums[i] == nums[i - 1]: continue for j in range(i+1, nums_len - 2): left = j + 1 right = nums_len - 1 if j != i + 1 and nums[j] == nums[j-1]: continue while left < right: nsums = nums[i] + nums[j] + nums[left] + nums[right] if nsums == target: res.append([nums[i], nums[j], nums[left], nums[right]]) while left < right and nums[left+1] == nums[left]: left += 1 while left < right and nums[right-1] == nums[right]: right -= 1 left += 1 right -= 1 elif nsums > target: right -= 1 else: left += 1 return res
0 0
- LeetCode[Array]---- 4Sum
- LeetCode--Array---4Sum
- leetcode.array--18. 4Sum
- 18. 4Sum leetcode (array) 总结
- 18. 4Sum--Array--LeetCode--C++
- LeetCode[Array]----3Sum
- 15.3sum leetcode(array)
- Leetcode - Pointers/Array - Two sum
- LeetCode[Array]----3Sum Closest
- LeetCode: Split Array Largest Sum
- 1.Two Sum leetcode(array)
- LeetCode-Array-1. Two Sum
- [Leetcode] Split Array Largest Sum
- LeetCode刷题【Array】 Two Sum
- leetcode.array--1. Two Sum
- Array -- Leetcode problem1. Two Sum
- leetcode.array--15. 3Sum
- leetcode.array--39. Combination Sum
- 数据分类:决策树Decision Tree
- 代码规范工具-Checkstyle使用手册
- 【整理】python 3.x爬虫
- 如何禁止App在后台运行以及如何保存和恢复App的状态
- Android官方API Demo学习之联系人获取
- LeetCode[Array]---- 4Sum
- iOS应用跳转问题之:应用跳转
- 谈需求分析工作
- 文字生成二维码
- 【QT】:QT实现连接opencv,版本为2.3.10
- LeetCode 190. Reverse Bits
- live555
- 欢迎使用CSDN-markdown编辑器
- Windows下gvim的编码问题