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的更多相关文章

  1. 【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 ...

  2. 【JAVA、C++】LeetCode 002 Add Two Numbers

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  3. 【JAVA、C++】LeetCode 022 Generate Parentheses

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  4. 【JAVA、C++】LeetCode 010 Regular Expression Matching

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  5. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  6. 【JAVA、C++】LeetCode 007 Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...

  7. 【JAVA、C++】LeetCode 006 ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  8. 【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 ...

  9. 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, ...

随机推荐

  1. POJ-1273 Drainage Ditches 最大流Dinic

    Drainage Ditches Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 65146 Accepted: 25112 De ...

  2. codevs1225 八数码难题

    题目描述 Description Yours和zero在研究A*启发式算法.拿到一道经典的A*问题,但是他们不会做,请你帮他们.问题描述 在 3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数 ...

  3. POJ1065 Area

    Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 18499   Accepted: 5094 Description You ...

  4. Android消息通知(notification)和PendingIntent传值

    通知栏的自定义布局:转:http://blog.csdn.net/vipzjyno1/article/details/25248021 拓展 实现自定义的通知栏效果: 这里要用到RemoteViews ...

  5. easyui form 方式提交数据

    http://ldzyz007.iteye.com/blog/2067540 <form id="ff" method="post">      . ...

  6. Struts2 自定义Result

    注意:我只要是解决自定义返回Json 和异常处理问题 新建一个类 AjaxResult   继承 StrutsResultSupport 看看代码吧 public class AjaxResult e ...

  7. 2层Xml读取类

    配置文件 <?xml> <root> <parent name="C"> <child name="C1">Sp ...

  8. thinkphp开发规范

    1.编写目的     为了更好的提高技术部的工作效率,保证开发的有效性和合理性,并可最大程度的提高程序代码的可读性和可重复利用性,指定此规范.开发团队根据自己的实际情况,可以对本规范进行补充或裁减. ...

  9. 使用 PHP 和 Apache Solr 实现企业搜索

    原文链接:http://www.ibm.com/developerworks/cn/opensource/os-php-apachesolr/   http://blog.csdn.net/hzcyc ...

  10. Apache22中配置虚拟主机(Apache VirtualHost)

    Apache VirtualHost的作用就是可以让一个apache为多个域名服务,相当于一个服务器挂了N多个网站,举个例子: 我的apache服务器,ip为x.x.x.x,我有两个域名www.too ...