【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, ...
随机推荐
- awk多文件操作
awk 多文件操作2种实现方法 我们经常会将2个有关联文本文件进行合并处理.分别从不同文件获取需要的列,然后, 整体输出到一起.awk进行多文件处理时候,常常会遇到2个方面问题,第一个是怎么样合并多个 ...
- ActiveRecord中andFilterWhere使用
查询数据库时 $model; if(!empty($name)) { $model->andWhere(['name'=>$name]); } 可以用andFilterWhere,自动的把 ...
- pthread_kill
别被名字吓到,pthread_kill可不是kill,而是向线程发送signal.还记得signal吗,大部分signal的默认动作是终止进程的运行,所以,我们才要用signal()去抓信号并加上处理 ...
- Linux下J2EE环境搭建
1.下载MyEclipse 2010的linux安装包. myeclipse-10.1-offline-installer-linux 2.将下载MyEclipse 2010的linux安装包,使用X ...
- 轻量级应用开发之(01)第一个IOS程序
一 IPhone轻量级开发 1. 开发环境 Mac 版本: OS X EICap 10.11.3 (15D21) XCode开发版本: Version 7.2.1 (7C1002) 2.简单分析 UI ...
- 高效图片轮播,两个imageView实现
本文是投稿文章,作者:codingZero 导语 在不少项目中,都会有图片轮播这个功能,现在网上关于图片轮播的框架层出不穷,千奇百怪,笔者根据自己的思路,用两个imageView也实现了图片轮播,这里 ...
- MyEclipse修改项目名称后,部署到 tomcat问题
问题描述: 修改项目名称后,部署到tomcat问题 解决方案: 项目->属性->myelcipse->web下,修 改web context root就可! 要在eclipse里面改 ...
- Linux下安装Nginx详细图解教程
什么是Nginx? Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器,在高连接并发的情况下N ...
- HTML 5 应用程序缓存
使用 HTML5,通过创建 cache manifest 文件,可以轻松地创建 web 应用的离线版本. 什么是应用程序缓存(Application Cache)? HTML5 引入了应用程序缓存,这 ...
- safeNet
把那4个dll丢到C:\Windows\SysWOW64里去重启IIS,再测试