Last active
October 8, 2018 05:40
-
-
Save hsaputra/4dadf0d9016ffd3d1d714150e520189c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class Solution { | |
| public List<List<Integer>> threeSum(int[] nums) { | |
| // test cases | |
| // nums invalid | |
| // no duplicates | |
| // sums to zero | |
| // Eg: [-1,0,1,2,-1,-4] | |
| if (nums == null || nums.length == 0) { | |
| return new LinkedList<List<Integer>>(); | |
| } | |
| // Find 3 elements sums to target, which is 0. | |
| final int target = 0; | |
| // Iterate and find 2 with windowing. | |
| List<List<Integer>> results = new LinkedList<List<Integer>>(); | |
| // To checks for dups easier, lets sort it | |
| // Eg: [-4, -1, -1, 0, 1, 2] | |
| Arrays.sort(nums); | |
| final int sLen = nums.length; | |
| for (int i = 0; i < sLen; i++) { | |
| // Avoid duplicate on main iterator values | |
| if (i > 0 && nums[i] == nums[i-1]) { | |
| continue; | |
| } | |
| int diff = target - nums[i]; | |
| int left = i + 1; | |
| int right = sLen - 1; | |
| // Lets check if we can find the 2 through windowing | |
| while (left < right && left < sLen && right > i) { | |
| int tmp = nums[left] + nums[right]; | |
| // if we find the pair then lets add them. | |
| if (tmp == diff) { | |
| // create entry and add to results. | |
| List<Integer> entry = new LinkedList<Integer>(); | |
| entry.add(nums[i]); | |
| entry.add(nums[left]); | |
| entry.add(nums[right]); | |
| results.add(entry); | |
| left++; | |
| // avoid left duplicates | |
| while (left < sLen && nums[left] == nums[left-1] && left < right) { | |
| left++; | |
| } | |
| right--; | |
| // avoid right duplicates | |
| while (right > i && nums[right] == nums[right + 1] && right > left) { | |
| right--; | |
| } | |
| } else { | |
| if (tmp > diff) { | |
| right--; | |
| } else { | |
| left++; | |
| } | |
| } | |
| } | |
| } | |
| return results; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.programcreek.com/2012/12/leetcode-3sum/