Check if duplicate to the previous number (To prevent redundant check)
using 2 pointer, make the initial number fixed so that the problem turns into 2 sum
2 pointers to check the and find sum which is 0
When update, just update left pointer until it has a different number from the last one (To prevent redundant), right pointer will be handled by existing logics
Code
publicList<List<Integer>>threeSum(int[] nums){/*
Idea:
1. Sort it
2. iterate the nums
3. Check if duplicate to the previous number
4. using 2 pointer, make the initial number fixed
so that the problem turns into 2 sum
5. 2 pointers to check the and find sum which is 0
6. When update, just update left pointer
right pointer will be handled by existing logics
*/Arrays.sort(nums);// Sort array to non-decreasingList<List<Integer>> res =newLinkedList<List<Integer>>();for(int i =0; i < nums.length -2;++i){// Avoid duplicate numbersif(i >0&& nums[i]== nums[i -1]){continue;}int l = i +1, r = nums.length -1;//Init. 2 pointers, low and high// Start to find 2sumwhile(l < r){int threeSum = nums[i]+ nums[l]+ nums[r];// Current sumif(threeSum >0){--r;}elseif(threeSum <0){++l;}else{// Found 0 condition!// Add the result to the array
res.add(newLinkedList<Integer>(Arrays.asList(nums[i], nums[l], nums[r])));++l;while(nums[l]== nums[l -1]&& l < r){++l;}}}}return res;}