【LeetCode】015.3Sum
来源:互联网 发布:db2执行sql脚本有换行 编辑:程序博客网 时间:2024/06/01 09:50
题目:
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)解答:
首先将nums按照升序排序,第一层循环中确定第一个数字,在第二层循环里,第二个和第三个数从两边向中间扫描,计算每次的结果sum
(1)sum为0,得到一组解
(2)sum > 0 ,过大,需要将第三个数往左移动
(3)sum < 0,过小,需要将第二数往右移动
为了避免重复的结果,每次移动时跳过重复的值;
代码:
import java.util.*;public class Solution { public List<List<Integer>> threeSum(int[] nums) {Arrays.sort(nums); // non-descending order is ensuredList<List<Integer>> ret = new ArrayList<List<Integer>>();for (int i = 0; i < nums.length; i++) {// skip duplicatewhile (i > 0 && i < nums.length && nums[i] == nums[i - 1])i++;int j = i + 1, k = nums.length - 1;while (j < k) {int sum = nums[i] + nums[j] + nums[k];// find one tripletif (sum == 0) {List<Integer> triplet = new ArrayList<Integer>(3);triplet.add(nums[i]);triplet.add(nums[j]);triplet.add(nums[k]);ret.add(triplet);j++;// skip duplicatewhile (j < k && nums[j] == nums[j - 1])j++;k--;// skip duplicatewhile (k > j && nums[k] == nums[k + 1])k--;} else if (sum > 0) {k--;while (k > j && nums[k] == nums[k + 1])k--;} else {j++;// skip duplicatewhile (j < k && nums[j] == nums[j - 1])j++;}}}return ret;}}
0 0
- 【LeetCode】015.3Sum
- 【Leetcode】Path Sum (Sum)
- 【Leetcode】Two Sum (Sum)
- 【Leetcode】3Sum (Sum)
- 【Leetcode】4Sum (Sum)
- leetcode:leetcode :Path Sum
- leetcode Path Sum && Path Sum ||
- Leetcode:2Sum,3Sum
- 【Leetcode】Path Sum II (Sum)
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- 链接qt下sqlite数据库
- KEIl工具之scatter file分散加载文件1
- 简单单调队列原理
- eclipse最有用快捷键整理
- 关于CSS分页栏
- 【LeetCode】015.3Sum
- 构造函数的相关知识
- Android 实现按两次返回键退出程序
- <Head First 设计模式>:复合模式:duck
- 接口
- cf437C 贪心算法
- HDOJ pi 2179
- .Net网络编程——服务端获取客户端连接
- [CentOS]CentOS7安裝SSH教學