思路 + 复杂度
用一个hashmap存数字及其出现的次数,用一个list存出现的数字(不重复的)。add:将元素存入hashmap和list。时间复杂度O(1),空间复杂度O(1)
find:遍历list,依次在map中寻找list中的每个数字能否组成一个要求的和。假设找到的num1和num2相等,还需要判断它是否出现了>=2次。时间复杂度O(n),空间复杂度(1)
代码
class TwoSum {
List<Integer> list;HashMap<Integer, Integer> map;/** Initialize your data structure here. */public TwoSum() {
list = new ArrayList<>();map = new HashMap<>();}/** Add the number to an internal data structure.. */public void add(int number) {
if (map.containsKey(number)) {
map.put(number, map.get(number) + 1);} else {
list.add(number);map.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 num : list) {
int restNum = value - num;if ((num == restNum && map.get(num) > 1) || (num != restNum && map.containsKey(restNum))) {
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);*/