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. 怎么让alert弹出框的内容可以换行?

    在要点击弹出的地方输入这样的代码: alert("文本框中共有字母a的个数为:"+num+"\n"+"他们在字符串的索引为:"+ind) 就 ...

  2. oracle存储过程执行中输出日志文件

    create or replace procedure p_outputdebug(a varchar2,b varchar2,c varchar2)is vFileName varchar2(100 ...

  3. BZOJ-2038 小Z的袜子(hose) 莫队算法

    2038: [2009国家集训队]小Z的袜子(hose) Time Limit: 20 Sec Memory Limit: 259 MB Submit: 5573 Solved: 2568 [Subm ...

  4. 【poj1090】 Chain

    http://poj.org/problem?id=1090 (题目链接) 题意 给出九连环的初始状态,要求将环全部取下需要走多少步. Solution 格雷码:神犇博客 当然递推也可以做. 代码 / ...

  5. Java输入、输入、IO流 类层次关系梳理

    本文主要关注在Java编程中涉及到的IO相关的类库.方法.以及对各个层次(抽线.接口继承)的流之间的关系进行梳理 相关学习资料 http://baike.baidu.com/view/1007958. ...

  6. UVA1220Party at Hali-Bula(树的最大独立集 + 唯一性判断)

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105116#problem/H 紫书P282 员工和直属老板只能选一个,最多选多少人 思路 ...

  7. ActivityInfo taskAffinity

    通常在Manifest里面使用 <application android:icon="@drawable/icon" android:label="@string/ ...

  8. Spring学习5-Spring整合JDBC及其事务处理(注解方式)

    一.整合的步骤   1.步骤一:首先要获得DataSource连接池(推荐使用B方式): 要对数据库执行任何的JDBC操作,需要有一个Connection.在Spring中,Connection对象是 ...

  9. ios开发 网络编程浅析(一)

    iphone包含了很多框架和库,从底层的套接字到不同层次的封装,可以方便地给程序添加网络功能. (1)BSD套接字.最底层的套接字,这是Unix网络开发常用的API.如果从其他系统移植程序,而程序用的 ...

  10. vsftpd 搭建与介绍

    CentOS Linux Vsftp服务器配置 CentOS Linux Vsftp服务器配置 1.开启防火墙ftp端口           vi /etc/sysconfig/iptables    ...