【JAVA、C++】LeetCode 018 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.
解题思路一:
四路夹逼,C++:
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > res;
if (num.size() < )
return res;
sort(num.begin(), num.end());
for (int i = ; i <= num.size() - ; i++) {
for (int j = i + ; j <= num.size() - ; j++) {
int k = j + , l = num.size() - ;
while (k < l) {
if (num[i] + num[j] + num[k] + num[l] < target)
k++;
else if (num[i] + num[j] + num[k] + num[l] > target)
l--;
else {
res.push_back({ num[i], num[j], num[k], num[l] });
k++;
l--;
while (num[k] == num[k - ] && k < l)
k++;
while (num[l] == num[l + ] && k < l)
l--;
}
}
while (j < num.size() - && num[j] == num[j + ])
j++;
}
while (i < num.size()- && num[i] == num[i + ])
++i;
}
return res;
}
};
解题思路二:
分治,存储所有2个元素的和,然后采用第一题2sum的思路求解即可,这样时间复杂度不过O(n^2)
JAVA实现如下:
static public List<List<Integer>> fourSum(int[] num, int target) {
Set<List<Integer>> set = new LinkedHashSet<List<Integer>>();
HashMap<Integer, List<Integer[]>> hm = new HashMap<Integer, List<Integer[]>>();
Arrays.sort(num);
for (int i = 0; i < num.length - 1; i++)
for (int j = i + 1; j < num.length; j++) {
int sum = num[i] + num[j];
Integer[] tuple = { num[i], i, num[j], j };
if (!hm.containsKey(sum))
hm.put(sum, new ArrayList<Integer[]>());
hm.get(sum).add(tuple);
}
HashSet<Integer> keys= new HashSet<Integer>(hm.keySet());
for (int key : keys) {
if (hm.containsKey(key)) {
if (hm.containsKey(target - key)) {
List<Integer[]> pairs1 = hm.get(key),pairs2 = hm.get(target - key);
for (int i = 0; i < pairs1.size(); ++i) {
Integer[] first = pairs1.get(i);
for (int j = 0; j < pairs2.size(); ++j) {
Integer[] second = pairs2.get(j);
if (first[1] != second[1] && first[1] != second[3]
&& first[3] != second[1]
&& first[3] != second[3]) {
List<Integer> tempList = Arrays.asList(first[0],
first[2], second[0], second[2]);
Collections.sort(tempList);
set.add(tempList);
}
}
}
hm.remove(key);
hm.remove(target - key);
}
}
}
return new ArrayList<List<Integer>>(set);
}
C++(TLE):
#include<string>
#include<vector>
#include<set>
#include<iterator>
#include <stdlib.h>
#include<unordered_map>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> res;
vector<vector<int>> result;
if (nums.size() < )
return result;
sort(nums.begin(), nums.end());
unordered_map<int, vector<vector<int>>> hm ;
for (int i = ; i < nums.size() - ; i++) {
for (int j = i + ; j < nums.size(); j++) {
int sum = nums[i] + nums[j];
vector<int> tuple = { nums[i], i, nums[j], j };
unordered_map<int, vector<vector<int>>>::iterator iter;
iter = hm.find(sum);
if (iter == hm.end()) {
vector<vector<int>> tempv;
hm.insert(unordered_map<int, vector<vector<int>>>::value_type(sum, tempv));
}
hm[sum].push_back(tuple);
}
}
set<int> keys;
unordered_map<int, vector<vector<int>>>::iterator iter;
for (iter = hm.begin(); iter != hm.end(); iter++) {
keys.insert(iter->first);
}
for (int key : keys) {
unordered_map<int, vector<vector<int>>>::iterator iter;
iter = hm.find(key);
if (iter != hm.end()){
unordered_map<int, vector<vector<int>>>::iterator iter;
iter = hm.find(target - key);
if (iter != hm.end()){
vector<vector<int>> pairs1 = hm[key], pairs2 = hm[target - key];
for (int i = ; i < pairs1.size(); ++i) {
vector<int> first = pairs1[i];
for (int j = ; j < pairs2.size(); ++j) {
vector<int> second = pairs2[j];
if (first[] != second[] && first[] != second[]
&& first[] != second[]
&& first[] != second[]) {
vector<int> tempList = { first[],first[], second[], second[] };
sort(tempList.begin(), tempList.end());
res.insert(tempList);
}
}
}
hm.erase(key);
hm.erase(target - key);
}
}
}
copy(res.begin(), res.end(), back_inserter(result));
return result;
}
};
【JAVA、C++】LeetCode 018 4Sum的更多相关文章
- 【JAVA、C++】LeetCode 005 Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...
- 【JAVA、C++】LeetCode 002 Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- 【JAVA、C++】LeetCode 022 Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- 【JAVA、C++】 LeetCode 008 String to Integer (atoi)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【JAVA、C++】LeetCode 007 Reverse Integer
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...
- 【JAVA、C++】LeetCode 006 ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...
- 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, ...
随机推荐
- Mathematical operation
(1)Using let let result=2+1 let result=2-1 let result=2*1 let result=2/1(2) Using bracket echo $(($p ...
- 【Matplotlib】 标注一些点
相关的文档: Annotating axis annotate() command 标注的代码如下: ... t = 2 * np.pi / 3 plt.plot([t, t], [0, np.cos ...
- 20.(转)Android的样式(Style)和主题(Theme)
Android上的Style分为了两个方面: 1,Theme是针对窗体级别的,改变窗体样式: 2,Style是针对窗体元素级别的,改变指定控件或者Layout的样式. Android系统的themes ...
- BZOJ-2756 奇怪的游戏 黑白染色+最大流+当前弧优化+二分判断+分类讨论
这个题的数据,太卡了,TLE了两晚上,各种调试优化,各种蛋疼. 2756: [SCOI2012]奇怪的游戏 Time Limit: 40 Sec Memory Limit: 128 MB Submit ...
- UvaLive 5026 Building Roads
传送门 Time Limit: 3000MS Description There is a magic planet in the space. There is a magical country ...
- codeforce626C.Block Towers(二分)
C. Block Towers time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...
- display & visibility区别
http://www.cnblogs.com/zhangran/archive/2012/08/29/2662459.html 说明:在学习css的过程中由于其中包含太多的元素.属性等等,总有许多是自 ...
- background总结
1. background-position background-position的百分比属性规则是:图片本身(x%,y%)的那个点,与背景区域的(x%,y%)的那个点重合. 具体可参考: http ...
- Linux下如何搭建VPN服务器(转)
VPN服务器的配置与应用 实验场景 通过将Linux配置VPN服务器允许远程计算机能够访问内网. 我的目的: 现在需要开发第三方接口,而第三方接口有服务器IP地址鉴权配置,这样在本地开发出来的程序每次 ...
- int(11)最大长度是多少,MySQL中varchar最大长度是多少(转)
int(11)最大长度是多少,MySQL中varchar最大长度是多少? int(11)最大长度是多少? 在SQL语句中int代表你要创建字段的类型,int代表整型,11代表字段的长度. 这个11代表 ...