【leetcode】3SUM

来源:互联网 发布:独立域名和二级域名 编辑:程序博客网 时间:2024/06/05 03:55

题目:

Given an array S of n integers, are there elements abc 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问题转化为2sum问题,用O(n)时间遍历数组,对于每个元素num[i],找到2sum之和为-num[i]的元素,2sum时间复杂度可以为O(n*lgn),因为排序只需要一次,所以3sum的时间复杂度为O(n^2) + O(n*lgn)=O(n^2)。或者借助hashmap,时间复杂度依然是O(n^2)。


代码:

import java.util.ArrayList;import java.util.Arrays;public class Solution {private ArrayList<ArrayList<Integer>> list;    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {list = new ArrayList<ArrayList<Integer>>();Arrays.sort(num);for (int i = 0; i <= num.length - 3; i++) {if (i != 0 && num[i] == num[i - 1]) {continue;}twoSum(num, i, i + 1, num.length - 1);}return list;}private void twoSum(int[] num, int i, int begin, int end) {while (begin < end) {int sum = num[begin] + num[end];if (sum == -num[i]) {ArrayList<Integer> tmpList = new ArrayList<Integer>();tmpList.add(num[i]);tmpList.add(num[begin]);tmpList.add(num[end]);list.add(tmpList);begin++;end--;while (begin < end && num[begin] == num[begin - 1]) {begin++;}while (begin < end && num[end] == num[end + 1]) {end--;}}else if (sum < -num[i]) {begin++;} else if (sum > -num[i]){end--;}}}public static void main(String[] args) {int num[] = {-1,0,1,2,-1,-4};System.out.println(new Solution().threeSum(num));}}


0 0