1. 程式人生 > >Leetcode題解 15. 3Sum

Leetcode題解 15. 3Sum

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 static 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&&nums[i]<=0;i++){
           if
(i>0 && nums[i]==nums[i-1])continue; int l=i+1; int r=nums.length-1; while(l<r){ int sum=nums[l]+nums[i]+nums[r]; if(sum==0){ List<Integer> list=new ArrayList<Integer>(); list
.add(nums[i]); list.add(nums[l]); list.add(nums[r]); result.add(list); l++; r--; while(l<r&&nums[l]==nums[l-1]) l++; while(l<r&&nums[r]==nums[r+1]) r--; }else if(sum>0){ r--; }else{ l++; } } } return result; } }