3sum leetcode

来源:互联网 发布:淘宝图片什么格式 编辑:程序博客网 时间:2024/06/10 13:40

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: 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]]
package leetcode;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Solution {    public List<List<Integer>> threeSum(int[] nums) {    Arrays.sort(nums);    List<List<Integer>> result=new ArrayList<List<Integer>>();    for(int i=0;i<nums.length-2;){        int li=i+1, hi=nums.length-1;    while(li<hi){    if(nums[li]+nums[hi]+nums[i]==0){    List<Integer> l=new ArrayList<Integer>();    l.add(nums[i]);    l.add(nums[li]);    l.add(nums[hi]);    result.add(l);    while(nums[hi]==nums[hi-1]&&li<hi){    hi--;            }    hi--;    while(nums[li]==nums[li+1]&&li<hi){    li++;            }    li++;    }else if(nums[li]+nums[hi]>0-nums[i]){    while(li<hi&&nums[hi]==nums[hi-1]){    hi--;            }    hi--;    }else if(nums[li]+nums[hi]<0-nums[i]){    while(li<hi&&nums[li]==nums[li+1]){    li++;            }    li++;    }    }        while(i<nums.length-2&&nums[i]==nums[i+1]){        i++;        }        i++;    }    return result;    }    public static void main(String[]args){    Solution s=new Solution();    System.out.println(s.threeSum(new int[]{-2,-3,0,0,-2}));    }}


0 0
原创粉丝点击