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);
     */
  • 相关阅读:
    实验4-1-5 韩信点兵 (10分)
    实验4-1-6 求分数序列前N项和 (15分)
    实验7-1-5 选择法排序 (20分)
    实验7-1-2 求最大值及其下标 (20分)
    第一次个人编程作业
    3.Vue.js-目录结构
    2.VUEJS-安装
    1.Vuejs-第一个实例
    Mybatis通用Mapper介绍与使用
    商城项目团购之定时任务2
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10050186.html
Copyright © 2011-2022 走看看