zoukankan      html  css  js  c++  java
  • 170. Two Sum III

    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.

    Example 1:

    add(1); add(3); add(5);
    find(4) -> true
    find(7) -> false
    

    Example 2:

    add(3); add(1); add(2);
    find(3) -> true
    find(6) -> false

    用hashmap存新加入的元素和频率

    add直接把元素加进hashmap。find遍历整个map,分两种情况,如果k和v相同,对应频率要大于1;如果不同,只要map中存在key=v即可。

    时间:add - O(1), find - O(N),空间:O(N)

    class TwoSum {
        HashMap<Integer, Integer> map;
    
        /** Initialize your data structure here. */
        public TwoSum() {
            map = new HashMap<>();
        }
        
        /** Add the number to an internal data structure.. */
        public void add(int number) {
            map.put(number, map.getOrDefault(number, 0) + 1);
        }
        
        /** Find if there exists any pair of numbers which sum is equal to the value. */
        public boolean find(int value) {
            for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
                int k = entry.getKey();
                int v = value - k;
                if((k != v && map.containsKey(v)) || (k == v && map.get(v) > 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);
     */
  • 相关阅读:
    02-vue过滤器和键盘修饰符
    01-vue指令
    webpack
    笔记:随机生成数、字符串
    笔记:long、longlong、int、float、NSString相互转换
    关于NSStringFromClass的一点见解
    iOS中UITextField常用设置和方法
    iOS 倒计时的一种实现
    iOS UITextField的代理<UITextFieldDelegate>的几点笔记
    iOS 单例模式简单实例
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10050186.html
Copyright © 2011-2022 走看看