leetcode 3sum

来源:互联网 发布:万方数据库论文官网 编辑:程序博客网 时间:2024/06/16 12:25

原题: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.


题意:给定一个数组num,求数组中三个数字相加为0的所有组合

思路:和上一篇twoSum类似,注意不同的地方。twoSum解是唯一的,而3sum不一定是唯一的

           基本的想法还是暴力搜索,时间复杂度O(n^3),不是理想的答案

           由于3sum是建立在twoSum的基础上的,可以选择固定一个数字,让余下的数字进行twoSum的操作。

           和twoSum不一样的地方是,twoSum使用了hashMap,在3sum中当然也可以使用HashMap,但是用hashMap有一个重复解的问题(twoSum只有一个解,所以不考虑重复解问题)。这里使用一种更好的方法,头尾指针法,前提是要进行排序,排序后让两个指针分别指向数组的头和尾,不断往中间移动两个指针,获取到所有的解,代码如下:

import java.util.ArrayList;import java.util.Arrays;public class Solution {    private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {        Arrays.sort(num);    for(int i = 0;i<num.length-2;i++)    {            if(i>0 && num[i] == num[i-1])    continue;    threeSumHelp(num[i],num,i+1);    }    return result;    }    public void threeSumHelp(int value,int[] num,int low)    {    int target = 0 - value;    int high = num.length-1;    while(low<high)    {    if(num[low] + num[high] == target)//获得了一个解    {    ArrayList<Integer> ans = new ArrayList<Integer>();    ans.add(value);    ans.add(num[low]);    ans.add(num[high]);    result.add(ans);    low++;    high--;    while(num[low] == num[low-1] && low<=high)    low++;    while(num[high] == num[high+1] && low<=high)    high--;    }    else if(num[low] + num[high]>target){high--;}    else {    low++;}    }    }}


时间复杂度为 排序O(nlogn) + O(n^2) = O(n ^ 2 )

由于排序的时间复杂度低于 O(n^2),因此先进行排序再作处理。这样在不耗费空间的前提下,完成程序。

原创粉丝点击