三刷Two Sum III - Data structure design

Easy

这次写得没有只用一个hashMap方法节省空间,记住这道题最优化的解法就是只用一个hashMap. 而且这道题很特别的是遍历到了 for (Map.Entry entry : map.entrySet()) entrySet()

class TwoSum {
    List list;
    /** Initialize your data structure here. */
    public TwoSum() {
        list = new ArrayList();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        list.add(number);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        Collections.sort(list);
        Map map = new HashMap<>();
        for (int i = 0; i < list.size(); i++){
            if (map.containsKey(value - list.get(i))){
                return true;
            } 
            map.put(list.get(i), i);
        }
        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);
 */

你可能感兴趣的:(三刷Two Sum III - Data structure design)