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. Type-Length-Value编码

    Within data communication protocols, optional information may be encoded as a type-length-value or T ...

  2. Erlang第二课 ---- bit串

    Erlang是被设计来用在电信设备中的,这意味着需要处理大量的二进制数据.也正因为如此,Erlang把binary和binary string提升到了一个相当高的位置,提供了极为丰富的操作机制.当然, ...

  3. C#通过编程方式实现Ping

    代码是照着书敲的,贴出来方便平时参考 using System; using System.Collections.Generic; using System.Linq; using System.T ...

  4. 打印多边形的菱形(for的嵌套)

    Console.WriteLine("请输入一个数字,会出现一个多边的菱形:"); int n = Convert.ToInt32(Console.ReadLine()); ; i ...

  5. HTML 5 应用程序缓存

    使用 HTML5,通过创建 cache manifest 文件,可以轻松地创建 web 应用的离线版本. 什么是应用程序缓存(Application Cache)? HTML5 引入了应用程序缓存,这 ...

  6. 关于talbeViewCell一点感想

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPa ...

  7. 基于REST架构的Web Service设计

    来自: http://www.williamlong.info/archives/1728.html 先前我曾经介绍过利用Apache Axis实现基于SOAP的Web Service实现技术和相关代 ...

  8. WINDOWS渗透与提权总结(1)

    旁站路径问题: 1.读网站配置. 2.用以下VBS: 01 On Error Resume Next 02   03 If (LCase(Right(WScript.Fullname, 11)) = ...

  9. C# 类型参数的约束

    在定义泛型类时,可以对客户端代码能够在实例化类时用于类型参数的类型种类施加限制.如果客户端代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误.这些限制称为约束.约束是使用 where 上 ...

  10. systemctl 命令的用法

    对比表,以 apache / httpd 为例 任务 旧指令 新指令 使某服务自动启动 chkconfig --level 3 httpd on systemctl enable httpd.serv ...