Advertisement
sweet1cris

Untitled

Jan 9th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. public class TwoSum {
  2.  
  3.     private List<Integer> list = null;
  4.     private Map<Integer, Integer> map = null;
  5.     public TwoSum() {
  6.         list = new ArrayList<Integer>();
  7.         map = new HashMap<Integer, Integer>();
  8.     }
  9.  
  10.     // Add the number to an internal data structure.
  11.     public void add(int number) {
  12.         // Write your code here
  13.         if (map.containsKey(number)) {
  14.             map.put(number, map.get(number) + 1);
  15.         } else {
  16.             map.put(number, 1);
  17.             list.add(number);
  18.         }
  19.     }
  20.  
  21.     // Find if there exists any pair of numbers which sum is equal to the value.
  22.     public boolean find(int value) {
  23.         // Write your code here
  24.         for (int i = 0; i < list.size(); i++) {
  25.             int num1 = list.get(i), num2 = value - num1;
  26.             if ((num1 == num2 && map.get(num1) > 1) ||
  27.                 (num1 != num2 && map.containsKey(num2)))
  28.                 return true;
  29.         }
  30.         return false;
  31.     }
  32. }
  33.  
  34.  
  35. // Your TwoSum object will be instantiated and called as such:
  36. // TwoSum twoSum = new TwoSum();
  37. // twoSum.add(number);
  38. // twoSum.find(value);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement