Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, abc)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
(-1, 0, 1)
(-1, -1, 2)

解题思路:

3Sum对初学者估计是丈二和尚摸不着头脑,其实NSum都有固定的解法。参考链接:

http://tech-wonderland.net/blog/summary-of-ksum-problems.html

基本上所有思路都是排序后查找,防止出现List的重复,因此想到使用set类型,JAVA实现如下:

static public List<List<Integer>> threeSum(int[] num) {
LinkedHashSet<List<Integer>> set = new LinkedHashSet<List<Integer>>();
if (num.length <= 2)
return new ArrayList<List<Integer>>(set);
final int tar = 0;
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
int j = i + 1, k = num.length - 1;
while (j < k) {
if (num[i] + num[j] + num[k] < tar)
j++;
else if (num[i] + num[j] + num[k] > tar)
k--;
else {
set.add(Arrays.asList(num[i], num[j], num[k]));
j++;
k--;
}
}
}
return new ArrayList<List<Integer>>(set);
}

结果第一次提交Time Limit Exceeded,第二次提交竟然神奇般的通过了!!!时间425ms,估计也是擦线飘过。

原因在于set每添加一个元素都会和set中元素进行比较,也就是说需要一次遍历,这样每添加一个元素,时间开销就会比较大,因此修改代码如下,时间322 ms:

static public List<List<Integer>> threeSum(int[] num) {
ArrayList<List<Integer>> list = new ArrayList<List<Integer>>();
final int tar = 0;
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
int j = i + 1, k = num.length - 1;
while(i < k && num[i]==num[i+1])
i++;
while (j < k) {
if (num[i] + num[j] + num[k] < tar)
j++;
else if (num[i] + num[j] + num[k] > tar)
k--;
else {
list.add(Arrays.asList(num[i], num[j], num[k]));
j++;
k--;
while(j<k&&num[j]==num[j-1])
j++;
while(k>j&&num[k]==num[k+1])
k--;
}
}
}
return list;
}

C++:

 class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
if (nums.size() <= )
return res;
const int tar = ;
sort(nums.begin(),nums.end());
for (int i = ; i < nums.size() - ; i++) {
int j = i + , k = nums.size() - ;
while (i < k && nums[i] == nums[i + ])
i++;
while (j < k) {
if (nums[i] + nums[j] + nums[k] < tar)
j++;
else if (nums[i] + nums[j] + nums[k] > tar)
k--;
else {
res.push_back({ nums[i], nums[j], nums[k]});
j++;
k--;
while (j<k&&nums[j] == nums[j - ])
j++;
while (k>j&&nums[k] == nums[k + ])
k--;
}
}
}
return res;
}
};

【JAVA、C++】LeetCode 015 3Sum的更多相关文章

  1. 【JAVA、C++】LeetCode 016 3Sum Closest

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. 【前端】Sublime text3 插件HTML/CSS/JS prettify 格式化代码

    1.首先安装插件 菜单的preference->packages control,然后输入install .. 回车,再输入HTML/CSS/JS prettify 再回车,重启后就可以了. 2 ...

  2. POJ1325 Machine Schedule

    Description As we all know, machine scheduling is a very classical problem in computer science and h ...

  3. USACO 3.2 msquare 裸BFS

    又是个裸BFS... 和西安网赛那道1006一样的,只不过加上了要记录方案.顺便复习map 记录方案直接在bfs队列的结点里加一个vector<int> opt,把从开头一直到当前结点的操 ...

  4. Bzoj2440 完全平方数

    Time Limit: 10000MS   Memory Limit: 131072KB   64bit IO Format: %lld & %llu Description 小 X 自幼就很 ...

  5. 转:Linux集群-----HA浅谈

    通过特殊的软件将若干服务器连接在一起并提供故障切换功能的实体我们称之为高可用集群.可用性是指系统的uptime,在7x24x365的工作环境中,99%的可用性指在一年中可以有87小时36分钟的DOWN ...

  6. POJ1651Multiplication Puzzle(矩阵链乘变形)

    Multiplication Puzzle Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8040   Accepted: ...

  7. 大数据分析与机器学习领域Python兵器谱

    http://www.thebigdata.cn/JieJueFangAn/13317.html 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开发语言是C/ ...

  8. --hdu 1050 Moving Tables(贪心)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1050 AC code: #include<stdio.h> #include<str ...

  9. Java & C++ 大数计算

    Java--大数计算,妈妈再也不用担心我的学习了 . BigInteger 英文API: http://docs.oracle.com/javase/8/docs/api/ 中文API: http:/ ...

  10. pyenv 以及 virtualenv

    244 pyenv global 3.5.1 245 which python 246 python 247 pip install virtualenv 248 ls 249 pwd 250 ls ...