Two Sum III - Data structure design LT170

Design and implement a TwoSum class. It should support the following operations:add and find.

add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.

For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false 

Idea 1. Similar to Two Sum LT1, if numbers are unique, set would be enough, otherwise map to store frequency for each number. 遍历hashmap, 对于每个数num,找target - num,

record[num] >= 2 if target - num = num

record[target - num] >= 1 if target - num != num

Time complexity: O(1) for add, O(n) for find, or alternatively add set to store the sum, so that O(n) for add, O(1) for find

Space complexity: O(n)

 1 public class TwoSum {
 2     private Map<Integer, Integer> record = new HashMap<>();
 3 
 4     public void add(int number) {
 5         record.put(number, record.getOrDefault(number, 0) + 1);
 6     }
 7 
 8     public boolean find(int value) {
 9         for(int key: record.keySet()) {
10             int another = value - key;
11             if(key == another) {
12                 if(record.get(another) >= 2) {
13                     return true;
14                 }
15             }
16             else {
17                 if(record.containsKey(another)){
18                     return true;
19                 }
20             }
21         }
22         return false;
23     }
24 
25     public static void main(String[] args) {
26         TwoSum subject = new TwoSum();
27         subject.add(1);
28         subject.add(3);
29         subject.add(4);
30         System.out.println(subject.find(4));
31         System.out.println(subject.find(7));
32     }
33 }

slightly more conciser:

 1 public class TwoSum {
 2     private Map<Integer, Integer> record = new HashMap<>();
 3 
 4     public void add(int number) {
 5         record.put(number, record.getOrDefault(number, 0) + 1);
 6     }
 7 
 8     public boolean find(int value) {
 9         for(int key: record.keySet()) {
10             int another = value - key;
11             if((key == another && record.get(another) >= 2)
12                || (key != another && record.containsKey(another))){
13                 return true;
14             }
15         }
16         return false;
17     }
18 }

posted on 2019-03-30 07:48  一直走在路上  阅读(111)  评论(0)    收藏  举报

导航