170. 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

一刷
題解:
用map來保存value和1表示出現1次,2表示出現2次。尋找的時候。遍歷map的key,然后判斷value - key在不在map中

public class TwoSum {
    Map<Integer, Integer> hm;
    
    /** Initialize your data structure here. */
    public TwoSum() {
        hm = new HashMap<>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if(hm.containsKey(number)) hm.put(number, 2);
        else hm.put(number,1);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        Iterator<Integer> iter = hm.keySet().iterator();
        while(iter.hasNext()){
            int num1 = iter.next();
            int num2 = value - num1;
            if(hm.containsKey(num2)){
                if(num1 != num2 || hm.get(num2) == 2) 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);
 */
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容