Two Sum III - Data structure design Leetcode
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
public class TwoSum { Map<Integer, Integer> hs; /** Initialize your data structure here. */ public TwoSum() { hs = new HashMap<>(); } /** Add the number to an internal data structure.. */ public void add(int number) { if (hs.containsKey(number)) { hs.put(number, hs.get(number) + 1); } else { hs.put(number, 1); } } /** Find if there exists any pair of numbers which sum is equal to the value. */ public boolean find(int value) { for (int n : hs.keySet()) { if (hs.containsKey(value - n)) { if (value - n == n && hs.get(n) == 1) { continue; } return true; } } return false; } }
还有一种思路是,add的时候就把所有可能的和都求出来,存在一个hashset里面,find方法就只需要O(1).
add的时候如果已经contain了,就把当前的sum加上一个本number * 2,如果不contain,就把现有的num都加一遍,然后加到sum的set里去。
代码不写了。。。
重做这道题居然还是有点不顺,这下无意间把所有的可能都写了一遍。。。= =
需要注意的就是如果add(2), find(4)这种情况应该是false。