170 Two Sum III - Data structure design
class TwoSum { HashMap<Integer, Integer> map; /** Initialize your data structure here. */ public TwoSum() { map = new HashMap<>(); } /** Add the number to an internal data structure.. */ public void add(int number) { Integer freq = map.get(number); if(freq == null){ map.put(number, 1); }else{ map.put(number, freq + 1); } } /** Find if there exists any pair of numbers which sum is equal to the value. */ public boolean find(int value) { for(int element : map.keySet()){ /// map.keySet() int target = value - element; if(element == target && map.get(element) > 1){ return true; } if(element != target && map.containsKey(target)){ return true; } } return false; } }
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.
Example 1:
add(1); add(3); add(5); find(4) -> true find(7) -> false
Example 2:
add(3); add(1); add(2); find(3) -> true find(6) -> false
posted on 2018-08-10 15:25 猪猪🐷 阅读(118) 评论(0) 收藏 举报
浙公网安备 33010602011771号