`
huntfor
  • 浏览: 195213 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]4Sum

 
阅读更多

新博文地址:[leetcode]4Sum

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 和3Sum Closest ,只需要在3Sum的外层再加一层循环即可。不了解的请戳这里。时间复杂度为O(n^3),但是我在网上看到一个算法时间复杂度只有O(n^2),但是空间复杂度太大,而且网上只提供了算法思想,并没有给出实现,本以为O(n^3)过不去,因此把O(n^2)的算法实现了一下。代码太长太丑,阅览请慎重:

 

List<List<Integer>> result = new ArrayList<List<Integer>>();
	Set<String> duplicate = new HashSet<String>();
	public List<List<Integer>> fourSum(int[] num, int target) {
		if (num == null || num.length < 4) {
			return result;
		}
		HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
		Map<Integer, List<int[]>> twoSum = new HashMap<Integer, List<int[]>>();
		Set<Integer> processed = new HashSet<Integer>();
		for (int i = 0; i < num.length; i++) {
			hash.put(num[i], hash.containsKey(num[i]) ? hash.get(num[i]) + 1
					: 1);
			for (int j = i + 1; j < num.length; j++) {
				int[] node = new int[] { num[i], num[j] };
				if (twoSum.containsKey(num[i] + num[j])) {
					twoSum.get(num[i] + num[j]).add(node);
				} else {
					List<int[]> list = new ArrayList<int[]>();
					list.add(node);
					twoSum.put(num[i] + num[j], list);
				}
			}
		}
		for (int k : twoSum.keySet()) {
			if (processed.contains(k))
				continue;
			if (twoSum.containsKey(target - k)) {
				processed.add(k);
				if (target == k << 1) {
					for (int[] node1 : twoSum.get(k)) {
						for (int[] node2 : twoSum.get(k)) {
							if (node2 != node1) {
								process(node1, node2, hash);
							}
						}
					}
				} else {
					processed.add(target - k);
					List<int[]> list1 = twoSum.get(k);
					List<int[]> list2 = twoSum.get(target - k);
					for (int[] node1 : list1) {
						for (int[] node2 : list2) {
							process(node1, node2, hash);
						}
					}
				}

			}
		}
		return result;
	}
	private void process(int[] a, int[] b, HashMap<Integer, Integer> map) {
		int[] sum = new int[] { a[0], a[1], b[0], b[1] };
		Arrays.sort(sum);
		StringBuilder sb = new StringBuilder();
		Map<Integer, Integer> cloneMap = (HashMap<Integer, Integer>) map
				.clone();
		for (int i = 0; i < 4; i++) {
			sb.append(sum[i]);
			cloneMap.put(sum[i], cloneMap.get(sum[i]) - 1);
			if (cloneMap.get(sum[i]) < 0)
				return;
		}
		if (!duplicate.contains(sb.toString())) {
			duplicate.add(sb.toString());
			List<Integer> list = new ArrayList<Integer>();
			for(int i = 0; i < 4; list.add(sum[i++]));
			result.add(list);
		}
	}

 

 

 

 

分享到:
评论

相关推荐

    python数组双指针算法求和问题LeetCode2sum3sum4sum含代码

    双指针算法,python数组双指针算法求和问题LeetCode2sum3sum4sum含代码

    文档python数组双指针算法求和问题LeetCode2sum3sum4sum含代码

    文档python数组双指针算法求和问题LeetCode2sum3sum4sum含代码提取方式是百度网盘分享地址

    Leetcode two sum java 解法

    Leetcode two sum java 解法

    oj.leetcode 2sum 解

    oj.leetcode题解, 2sum, 运用hashtable解决这到问题,时间复杂度O(N)

    leetcode2sum-leetCodeSolutions:我对leetCode问题的解决方案

    leetcode 2sum leetCode解决方案 我对 leetCode 问题的解决方案 已解决的练习列表: 简单的: 2sum - 带有未排序的数组; O(n) 复杂度; 花了~3ms 2sum - 使用排序数组; O(n) 复杂度 罗马转整数; O(n) 复杂度 合并...

    leetcode2sum-Problems:编程问题的回购

    LC4: Longest Palindromic Substring [Medium] LC5: Median Of Two Sorted Arrays [Hard] LC6: Zigzag Conversion [Medium] LC7: Reverse Integer [Easy] LC8: String To Integer Atoi [Medium] LC9: Palindrome ...

    2sumleetcode-2SUM:使用先前地图的最快二和O(N)

    leetcode 2SUM 使用以前的地图最快的 2Sum O(N) 使用 unordered_map 比 map 快 以前的地图 là gì ? 上一张地图 đơn giản là 地图 nhưng thay vì ta cần một vòng for để khởi tạo 地图 thì ta khởi...

    leetcode2sum-Q1.-2Sum:力码研究1

    leetcode 2sum 2总和 力码研究1

    leetcode3sum-LeetCode:leetcode问题用C#解决

    3sum 力码 力扣算法 (注:“ :locked: " 表示你需要来自 Leetcode) # 标题 解决方案 困难 001 简单的 002 中等的 003 中等的 004 难的 005 中等的 006 简单的 007 简单的 008 简单的 009 简单的 010 难的 011 中等...

    leetcode3sum-leetcode-curation-topical:技术面试准备清单

    3sum leetcode-curation-topical 精选 Leetcode 问题,按主题/概念分类。 我的策展标准是问题必须是有价值的,而不仅仅是为了难而难。 有价值的问题通常可以以不同的时间/空间效率(通过使用各种数据结构)以多种...

    LeetCode -- Path Sum III分析及实现方法

    主要介绍了LeetCode -- Path Sum III分析及实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

    LeetCode最全代码

    18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers 26 | [Remove Duplicates from Sorted Array]...

    2sumleetcode-LeetCode:力码

    leetcode 轮廓 1_count_and_say.cpp - super_ugly_number.cpp - Detect_Pattern.cpp - degree_of_array.cpp - 键盘.cpp - 2Sum_Data_Structure_Design.cpp - shuffle_array.cpp - permutations.cpp - kth_missing_...

    leetcode3sumnlogn-learn-algorithm:学习算法

    leetcode 3sum nlogn 让我们研究算法 微电脑网 : 2018.09.06。 用 BFS 搜索,用 DP 解决。 我过去没能做到,但感觉很好。 : 2018.09.06。 起初,它以这样的方式重复,如果有什么变化,它会再次旋转。 -&gt; 超时 接下来...

    leetcode答案-LeetCode_1_TwoSum:LeetCode_1_TwoSum

    答案LeetCode_1_TwoSum LeetCode 问题:给定一个整数数组,找出两个数字,使它们相加为特定的目标数字。 函数 twoSum 应该返回两个数字的索引,使它们相加为目标,其中 index1 必须小于 index2。 请注意,您返回的...

    Two Sum leetcode c++

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2)...

    leetcode2sumc-leetcode:JavaScript版本leetcode中文版代码

    leetcode 2 sum c leetcode 力扣(Leetcode)编程题,JavaScript版本。 编号 中文题目 英文题目 题目描述 JavaScript 难度 1 Two Sum 简单 2 Add Two Numbers 中等 ...3Sum ...3Sum ...4Sum 中等 19 Remo

    程序员面试宝典LeetCode刷题手册

    18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Merge k Sorted Lists 24. Swap Nodes in Pairs 25. Reverse Nodes in k-Group 26...

    leetcode2sumc-leetcodeforjs:leetcodeforjs

    leetcode 2 sum c JS 算法与数据结构(LEETCODE) 环境安装 安装依赖 npm install --save-dev jest //单元测试 npm install babel-jest babel-core@^7.0.0-bridge.0 @babel/core regenerator-runtime babel-preset-env...

    leetcode.3sum-leetcode-practice:算法实践

    -4] 示例输出: [ [-1, 0, 1], [-1, -1, 2] ] 首先,我最自然的想法是简单地搜索给定数组中 3 个数字的所有可能组合,并找出满足请求的组合。 这该怎么做? 我们将遍历数组中的每个元素,对于每个元素,我们将搜索其...

Global site tag (gtag.js) - Google Analytics