两数之和-数据结构设计 · Two Sum

[抄题]:

设计b并实现一个 TwoSum 类。他需要支持以下操作:add 和 find
add -把这个数添加到内部的数据结构。
find -是否存在任意一对数字之和等于这个值

[思维问题]:

不知道为什么要用到ArrayList。

  1. find函数要一个个检查有没有某元素,题中没有原始定义的数据结构,所以要用。
  2. 为什么不用数组:add添加的元素数量不确定,需要动态添加。

[一句话思路]:

就是写两个方法就行了。

[画图]:

[一刷]:

  1. hashmap, list都是第一次用于新的数据结构中,定义为private,而且要在外面初始化。
  2. 类名是都要大写的,而且新类必须写出来。创建对象在新类里面。
  3. find add的参数都是一个数字。
  4. list中的每一个元素只需要插入一次,保持唯一性。

[总结]:

[复杂度]:

[英文数据结构,为什么不用别的数据结构]:

  1. 为什么用hashmap:find函数要一个个检查有没有某元素,题中没有原始定义的数据结构,所以要用。
  2. 不仅能检查有没有,还能检查次数,从而查出相同元素出现的次数。
  3. 为什么不用数组:add添加的元素数量不确定,需要动态添加。

[其他解法]:

[题目变变变]:

public class TwoSum {

    private List<Integer> list = null;
    private Map<Integer, Integer> map = null;
    public TwoSum() {
        list = new ArrayList<Integer>();
        map = new HashMap<Integer, Integer>();
    }

    // Add the number to an internal data structure.
    public void add(int number) {
        // Write your code here
        if (map.containsKey(number)) {
            map.put(number, map.get(number) + 1);
        } else {
            map.put(number, 1);
            list.add(number);
        }
    }

    // Find if there exists any pair of numbers which sum is equal to the value.
    public boolean find(int value) {
        // Write your code here
        for (int i = 0; i < list.size(); i++) {
            int num1 = list.get(i), num2 = value - num1;
            if ((num1 == num2 && map.get(num1) > 1) || 
                (num1 != num2 && map.containsKey(num2))) 
                return true;
        }
        return false;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8038542.html