原题链接在这里: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:
class TwoSum { HashMap<Integer, Integer> hm; /** Initialize your data structure here. */
public TwoSum() {
hm = new HashMap<Integer, Integer>();
} /** Add the number to an internal data structure.. */
public void add(int number) {
hm.put(number, hm.getOrDefault(number, 0) + 1);
} /** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for(Map.Entry<Integer, Integer> entry : hm.entrySet()){
int num1 = entry.getKey();
int num2 = value-num1;
if(hm.containsKey(num2) && (hm.get(num2)>1 || num1!=num2)){
return true;
}
}
return false;
}
} /**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/
考虑到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:
public class TwoSum {
HashSet<Integer> nums;
HashSet<Integer> sums; /** Initialize your data structure here. */
public TwoSum() {
nums = new HashSet<Integer>();
sums = new HashSet<Integer>();
} /** Add the number to an internal data structure.. */
public void add(int number) {
Iterator<Integer> it = nums.iterator();
while(it.hasNext()){
sums.add(it.next()+number);
}
nums.add(number);
} /** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
return sums.contains(value);
}
} /**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/