Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution 1:
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> returnList = new ArrayList<List<Integer>>();
        if(nums==null||nums.length < 2) return returnList;
        Arrays.sort(nums);
        int length = nums.length;
        for(int i=0;i<length;i++){
            
            if(i>0 && nums[i]==nums[i-1]) continue;
            int j=i+1;
            int k=length-1;
            int target = 0 - nums[i];
            while(j<k){
                if(nums[j]+nums[k] == target){
                    returnList.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    while(j<k && nums[j]==nums[j+1]) j++;
                    while(j<k && nums[k]==nums[k-1]) k--;
                    j++;k--;
                }else if(nums[j]+nums[k] < target){
                    j++;
                }else{
                    k--;
                }
            }
        }
        return returnList;
    }
}
rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

10 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

2 years ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

2 years ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

2 years ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.