leetcode-15
2016-05-24 21:56
302 查看
题目:
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.
Subscribe to see which companies asked this question
代码:
public class Solution {
public List<List<Integer>> threeSum(int[] nums){
int left, right;
int len = nums.length;
List<List<Integer>> res = new ArrayList<List<Integer>> ();
if(nums == null || nums.length < 3)
return res;
Arrays.sort(nums);
for(int i = 0; i < len - 2; i++){
if(i != 0 && nums[i] == nums[i - 1] )
continue;
left = i + 1;
right = len - 1;
while(left < right)
{
if(nums[i] + nums[left] + nums[right] == 0)
{
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
res.add(list);
left++;
right--;
while(left < right && nums[left] == nums[left-1])
left++;
while(left < right && nums[right] == nums[right+1])
right--;
}
else if(nums[i] + nums[left] + nums[right] < 0)
left++;
else
right--;
}
}
return res;
}
}
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)
Subscribe to see which companies asked this question
代码:
public class Solution {
public List<List<Integer>> threeSum(int[] nums){
int left, right;
int len = nums.length;
List<List<Integer>> res = new ArrayList<List<Integer>> ();
if(nums == null || nums.length < 3)
return res;
Arrays.sort(nums);
for(int i = 0; i < len - 2; i++){
if(i != 0 && nums[i] == nums[i - 1] )
continue;
left = i + 1;
right = len - 1;
while(left < right)
{
if(nums[i] + nums[left] + nums[right] == 0)
{
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
res.add(list);
left++;
right--;
while(left < right && nums[left] == nums[left-1])
left++;
while(left < right && nums[right] == nums[right+1])
right--;
}
else if(nums[i] + nums[left] + nums[right] < 0)
left++;
else
right--;
}
}
return res;
}
}
相关文章推荐
- SICP ex2-50
- Javascript之入门篇(一)
- linux shell编程
- Python 2.7.x 和 3.x 版本的重要区别
- linux基本命令(32)——gzip命令
- next_permutation函数
- dp 矩阵取数问题
- 并查集模板
- ASCII 、GB2312、GBK、GB18030、UTF-8、unicode 字符集编码详解
- [置顶] 冒泡排序
- 禅道项目管理
- Unity的StartCoroutines
- Linux多进程——利用fork()函数进行多进程编程
- Java的值传递
- Java的值传递
- 【一天一道LeetCode】#30. Substring with Concatenation of All Words
- 【一天一道LeetCode】#30. Substring with Concatenation of All Words
- jQuery高级技巧——DOM操作篇
- CentOS 6.5 下的截图方法
- javascript之DOM编程改变CSS样式(简易验证码显示)