【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, ...
随机推荐
- Oracle常用sql
Oracle不像Sqlserver,并没有提供l默认约束,但提供了默认值,效果一样.--------------------------- 在建表时设置默认约束-------------------- ...
- BZOJ1207 [HNOI2004]打鼹鼠
Description 鼹鼠是一种很喜欢挖洞的动物,但每过一定的时间,它还是喜欢 把头探出到地面上来透透气的.根据这个特点阿Q编写了一个打鼹鼠的游戏:在一个n*n的网格中,在某些时刻鼹鼠会在某一个网格 ...
- 抓包利器Fiddler
1).Fiddler安装 a.下载地址: http://fiddler2.com/get-fiddler b.安装:省略(下一步...下一步即可) 2).Fiddler配置 a.允许远程计算机连接Fi ...
- POJ 3258 River Hopscotch
River Hopscotch Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 11031 Accepted: 4737 ...
- SCU 4424(求子集排列数)
A - A Time Limit:0MS Memory Limit:0KB 64bit IO Format:%lld & %llu Submit Status Practice ...
- POJ2392Space Elevator(贪心+背包)
Space Elevator Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 9970 Accepted: 4738 De ...
- Linux 下模拟Http 的get or post请求(curl和wget两种方法)
一.get请求: 1.使用curl命令: curl "http://www.baidu.com" 如果这里的URL指向的是一个文件或者一幅图都可以直接下载到本地curl -i & ...
- Google Protocol Buffer 的使用和原理
Google Protocol Buffer 的使用和原理 Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,很适合做数据存储或 RPC 数据交换格式.它 ...
- Matlab的曲线拟合工具箱CFtool使用简介
http://phylab.fudan.edu.cn/doku.php?id=howtos:matlab:mt1-5 一. 单一变量的曲线逼近Matlab有一个功能强大的曲线拟合工具箱 cftool ...
- [Unity3D]引擎崩溃、异常、警告、BUG与提示总结及解决方法
1.U3D经常莫名奇妙崩溃. 一般是由于空异常造成的,多多检查自己的引用是否空指针. 2.编码切换警告提示. 警告提示:Some are Mac OS X (UNIX) and some ...