【LeetCode刷题】-- 170.两数之和III-数据结构设计

170.两数之和III-数据结构设计

【LeetCode刷题】-- 170.两数之和III-数据结构设计_第1张图片

方法:使用哈希表

class TwoSum {
    Map<Integer,Integer> map;
    public TwoSum() {
        map = new HashMap<>();
    }
    
    public void add(int number) {
        //key存元素,value为出现的次数
        map.put(number,map.getOrDefault(number,0) + 1);
    }
    
    public boolean find(int value) {
        //通过Map.entrySet遍历key和value
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            int diff = value - entry.getKey();
            if(diff != entry.getKey()){
                if(map.containsKey(diff)){
                    return true;
                }
            }
            //当前元素和差值相等,且当前元素出现次数大于1,返回true
            else{
                if( map.get(diff) > 1){
                    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);
 */

你可能感兴趣的:(LeetCode,leetcode,算法)