Created
November 19, 2019 21:04
-
-
Save aonurdemir/0576dd6bbf03927aa32d1d0c374bcf96 to your computer and use it in GitHub Desktop.
3sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
class Solution { | |
public List<List<Integer>> threeSum(int[] nums) { | |
int sum=0; | |
List<List<Integer>> ret = new ArrayList<List<Integer>>(); | |
Arrays.sort(nums); | |
for(int i=0; i < nums.length - 1; i++){ | |
if(i>0 && nums[i] == nums[i-1]) continue; | |
HashSet<Integer> set = new HashSet<Integer>(); | |
for(int j = i+1; j < nums.length; j++){ | |
int searched = sum - (nums[i] + nums[j]); | |
//look for the element already examined and pushed to set.(think this 'searched' integer as the third integer) | |
if(set.contains(searched)){ | |
List<Integer> list = new ArrayList<Integer>(); | |
list.add(nums[i]); | |
list.add(searched); | |
list.add(nums[j]); | |
ret.add(list); | |
//skip same numbers to prevent duplicate founds. | |
while (j + 1 < nums.length && nums[j+1] == nums[j]) ++j; | |
} | |
else{ | |
//push traversed integer to set. In other words, convert array to hash one by one | |
set.add(nums[j]); | |
} | |
} | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment