【JAVA、C++】LeetCode 015 3Sum
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, a ≤ b ≤ c)
- 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的更多相关文章
- 【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 ...
- 【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 ...
随机推荐
- 【HDU 2955】Robberies(DP)
题意是给你抢劫每个银行可获得的钱m和被抓的概率p,求被抓的概率小于P,最多能抢多少钱.01背包问题,体积是m,价值是p.被抓的概率不是简单相加,而应该是1−Π(1−p[i])DP:dp[i]表示抢到i ...
- 【 CodeForces 604A】B - 特别水的题2-Uncowed Forces
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=102271#problem/B Description Kevin Sun has jus ...
- poj 3734 矩阵快速幂+YY
题目原意:N个方块排成一列,每个方块可涂成红.蓝.绿.黄.问红方块和绿方块都是偶数的方案的个数. sol:找规律列递推式+矩阵快速幂 设已经染完了i个方块将要染第i+1个方块. a[i]=1-i方块中 ...
- ajax提交特殊字符的处理
前台页面用encodeURIComponent()这个js方法 rule=encodeURIComponent(rule);//对特殊字符编码 后台页面 java.net.URLDecoder url ...
- Emgu学习之(二)——图像读取、显示、保存
visual Studio Community 2015 工程和源代码:http://pan.baidu.com/s/1o6u5Fdw 内容 在这篇文章中将提到以下内容: 从文件中读取图像 Image ...
- 【wget】一条命令轻松备份博客(包括图片)
h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...
- Unity自动打包Apk
unity打包apk相对来说比较容易,相信出过的人都明白,出包过程,没有大的难度,一步一操作,一步一等待,繁琐耗时,不懂的人又代替不了.这时候需求就来了,如何简单的一键打包搞定,这个就稍微有点难度,当 ...
- mysql 用户方面的操作
1.只新建用户的操作 mysql -u root -p密码mysql> insert into mysql.user(Host,User,Password) values(‘localhost’ ...
- linux下可以禁用的一些服务
linux下多软件/多脚本之间的配合: 包括做好 “实体”和“配置”两个方面的事情 “实体”是指实实在在的脚本文件,服务脚本: “配置”是指其他与之交互的.协同工作的软件.脚本,要进行适当的配置,告知 ...
- WebRequest中的工厂方法模式