【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, ...
随机推荐
- Java编程思想学习(十一) 泛型
1.概要 generics enable types (classes and interfaces) to be parameters when defining classes, interfac ...
- Uva11134 Fabled Rooks
普通的贪心题. 虽然图是二维的,但可以把横向和纵向分开处理. 将区间按右端点排序,然后从区间左端点到右端点找第一个空位置放棋子即可. /*by SilverN*/ #include<algori ...
- [NOIP2011] 提高组 洛谷P1003 铺地毯
题目描述 为了准备一个独特的颁奖典礼,组织者在会场的一片矩形区域(可看做是平面直角坐标系的第一象限)铺上一些矩形地毯.一共有 n 张地毯,编号从 1 到n .现在将这些地毯按照编号从小到大的顺序平行于 ...
- VMWare File Format Learning && Use VHD File To Boot VMWare && CoreOS Docker Configuration And Running
目录 . Virtual Machine Introduce . Vmware Image File Format . VHD File Format . Convert VHD File Into ...
- 实现SVN与WEB同步解决方案(转)
实现SVN与WEB同步解决方案 1)设置WEB服务器根目录为/www/default 2)checkout一份SVN svn co svn://localhost/oplinux /www/defau ...
- jquery基础总结
什么是jQuery? 就是一个JavaScript函数库,开源的.jQuery能做什么 JavaScript是做什么的,jQuery就是做什么的,Jquery是对javas ...
- Socket网络编程(2)--服务端实现
中秋了,首先祝大家中秋快乐,闲着无事在家整一个socket的聊天程序,有点仿QQ界面,就是瞎折腾,不知道最后是不是能将所有功能实现. 如果你对socket不了解,请看这篇文章:http://www.c ...
- sturct stat 结构体中 st_mode 的含义
工作中遇到 else if( (s_buf.st_mode&S_IFMT) == S_IFDIR) return 2; else if( !(s_buf.st_mode&S_IFREG ...
- linux下syscall函数,SYS_gettid,SYS_tgkill
出处:http://blog.chinaunix.net/uid-28458801-id-4630215.html linux下syscall函数,SYS_gettid,SYS_tgkill ...
- 怎样把excel一列分成多列
1,选定要分列的列. 2,点击“数据”-“分列”. 3,在选项栏中设置如图 4,选择分隔符 4,看,分开了吧!