原题链接在这里:https://leetcode.com/problems/two-sum-iii-data-structure-design/
题目:
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
题解:
与Two Sum类似.
设计题目考虑trade off. 如果add 很多, find很少可以采用map方法.
简历HashMap保存key 和 key的frequency. find value时把HashMap的每一个key当成num1, 来查找HashMap是否有另一个value-num1的key.
num1 = value - num1时,检查num1的frequency是否大于1.
Time Complexity: add O(1). find O(n). Space: O(n).
AC Java:
1 class TwoSum { 2 3 HashMap<Integer, Integer> hm; 4 5 /** Initialize your data structure here. */ 6 public TwoSum() { 7 hm = new HashMap<Integer, Integer>(); 8 } 9 10 /** Add the number to an internal data structure.. */ 11 public void add(int number) { 12 hm.put(number, hm.getOrDefault(number, 0) + 1); 13 } 14 15 /** Find if there exists any pair of numbers which sum is equal to the value. */ 16 public boolean find(int value) { 17 for(Map.Entry<Integer, Integer> entry : hm.entrySet()){ 18 int num1 = entry.getKey(); 19 int num2 = value-num1; 20 if(hm.containsKey(num2) && (hm.get(num2)>1 || num1!=num2)){ 21 return true; 22 } 23 } 24 return false; 25 } 26 } 27 28 /** 29 * Your TwoSum object will be instantiated and called as such: 30 * TwoSum obj = new TwoSum(); 31 * obj.add(number); 32 * boolean param_2 = obj.find(value); 33 */
考虑到trade off, 上面用HashMap时add用O(1), find用O(n).
用两个Set分别存现有nums 和现有sums可以treade off.
这种设计适合少量add, 多量find操作.
Time Complexity: add O(n). find O(1). Space: O(n).
AC Java:
1 public class TwoSum { 2 HashSet<Integer> nums; 3 HashSet<Integer> sums; 4 5 /** Initialize your data structure here. */ 6 public TwoSum() { 7 nums = new HashSet<Integer>(); 8 sums = new HashSet<Integer>(); 9 } 10 11 /** Add the number to an internal data structure.. */ 12 public void add(int number) { 13 Iterator<Integer> it = nums.iterator(); 14 while(it.hasNext()){ 15 sums.add(it.next()+number); 16 } 17 nums.add(number); 18 } 19 20 /** Find if there exists any pair of numbers which sum is equal to the value. */ 21 public boolean find(int value) { 22 return sums.contains(value); 23 } 24 } 25 26 /** 27 * Your TwoSum object will be instantiated and called as such: 28 * TwoSum obj = new TwoSum(); 29 * obj.add(number); 30 * boolean param_2 = obj.find(value); 31 */