leetcode 15. 3Sum
来源:互联网 发布:大数据相关课程 编辑:程序博客网 时间:2024/06/05 16:32
题目
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: 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]]代码
public class Solution {public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); HashSet<String> repeat = new HashSet<String>(); Arrays.sort(nums); for (int i = 0 ; i <= nums.length - 2 ; i++) { int ans = 0 - nums[i]; int forw = i + 1; int back = nums.length - 1; while (forw < back) { if ((nums[forw] + nums[back]) == ans) { if (!repeat.contains(nums[i] + "&" + nums[forw])) { List<Integer> l = new ArrayList<Integer>(); l.add(nums[i]); l.add(nums[forw]); l.add(nums[back]); res.add(l); repeat.add(nums[i] + "&" + nums[forw]); } forw++; back--; }else if ((nums[forw] + nums[back]) < ans) { forw++; }else { back--; } } } return res; }}
0 0
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- [leetcode] 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- Leetcode 15. 3Sum
- LeetCode - 15. 3Sum
- [LeetCode]15. 3Sum
- Leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- 【leetcode】15. 3Sum
- Leetcode - 15. 3Sum
- 嵌入式面试题——ARM面试题(五)
- 友盟推送的使用
- PAT甲级练习1085. Perfect Sequence (25)
- java中的静态代理
- request:fail ssl hand shake error 微信小程序(已解决!!) TLS1.2版本配置
- leetcode 15. 3Sum
- python的基础知识
- Convert Sorted Array to Binary Search Tree
- sql server锁升级 / oracle没有锁升级
- Java OOP day05
- 设计模式笔记十三:代理模式
- CobarClient源码分析
- JavaVM和JNIEnv
- gcc/g++ 如何支持c11 / c++11标准编译