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
| private boolean sumsToTarget(int[] arr, int k) { | |
| Arrays.sort(arr); | |
| int lhs = 0, rhs = arr.length - 1; | |
| while (lhs < rhs) { | |
| int sum = arr[lhs] + arr[rhs]; | |
| if (sum == k) | |
| return true; | |
| else if (sum < k) | |
| lhs++; | |
| else rhs--; |
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
| private boolean sumsToTarget(int[] arr, int k) { | |
| HashSet values = new HashSet(); | |
| for (int i = 0; i < arr.length; i++) { | |
| if (values.contains(k - A[i])) return true; | |
| values.add(A[i]); | |
| } | |
| return false; | |
| } |
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
| private boolean sumsToTarget(int[] arr, int k) { | |
| Map<Integer, Integer> map = new HashMap<>(); | |
| for (int i = 0; i < nums.length; i++) { | |
| int complement = target - nums[i]; | |
| if (map.containsKey(complement)) { | |
| return new int[] { map.get(complement), i }; | |
| } | |
| map.put(nums[i], i); | |
| } | |
| throw new IllegalArgumentException("No two sum solution"); |
OlderNewer