3Sum
2014-02-06 05:28
218 查看
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.
View Code
public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(num.length<=2) return res; Arrays.sort(num); int len = num.length; for(int i=0;i<len;i++){ int sum = 0-num[i]; int start = i+1; int end = len-1; while(start<end){ if(num[start]+num[end]<sum){ start++; } else if(num[start]+num[end]>sum){ end--; } else{ ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(num[i]); temp.add(num[start]); temp.add(num[end]); res.add(temp); start++;end--; while(start<end && num[start-1]==num[start]){ start++; } while(start<end && num[end+1]==num[end]){ end--; } } } while(i<len-1 &&num[i+1]==num[i]){ i++; } } return res; } }
View Code
相关文章推荐
- 使用ACE读取INI文件
- Computer keyboard key explanations
- ubuntu下设置root帐户的密码
- POJ 1849 树的直径或者树形dp
- SSH登陆错误 WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
- Roman to Integer
- Integer to Roman
- ssh 错误 ssh: connect to host 192.168.1.106 port 22: Connection refused
- Regular Expression Matching
- String to Integer (atoi)
- ubuntu 下使用命令行方式实现无线上网
- Reverse Integer
- Longest Palindromic Substring
- [leet code] Count and Say
- ubuntu命令行下连接无线网络
- Add Two Numbers
- Median of Two Sorted Arrays
- Two Sum
- MYSQL出现乱码及用到的命令
- 簡單粗暴解決 Zsh Home 和 End 按鍵問題