Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. import javafx.util.Pair; //available in Java 1.8
  2.  
  3. public class Solution {
  4.  
  5. public static boolean twoSum(int[] a, int target) {
  6. Map<Integer, Pair> map = new HashMap<>();
  7. for(int i=0; i<a.length; i++) { //O(n) where n=a.length
  8. if (!map.containsKey(a[i])) { //don't insert duplicates
  9. map.put(a[i], new Pair<Integer, Integer>(target-a[i], i));
  10. //key is every unique element, value is a pair of numberToFind and position of element first found
  11. }
  12. }
  13. for(int i=0; i<a.length; i++) { //O(n) where n=a.length
  14. if (map.containsKey(target-a[i])) { //check if there exists numberToFind which adds up with current element to target
  15. if (i != (int) map.get(target-a[i]).getValue()) {
  16. //and if that numberToFind is at a different position in the array (handles duplicates)
  17. return true;
  18. }
  19. }
  20. }
  21. return false;
  22. }
  23.  
  24. public static void main(String[] args) {
  25. int[] a1 = {5, 4, 2, 4};
  26. int[] a2 = {5, 1, 2, 4};
  27. int[] a3 = {5, 4, 2, 3};
  28. int target = 8;
  29. System.out.println(twoSum(a1, target));
  30. System.out.println(twoSum(a2, target));
  31. System.out.println(twoSum(a3, target));
  32. }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement