• 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);
     */
  • 相关阅读:
    hxpCTF 2021 revvm Writeup
    微博自动化测试
    RosettaScripts学习笔记20211118
    amber进行分子动力学模拟水盒子和density需要注意的事项
    linux bash 字符串替换
    JQuery常用方法基础教程
    一些Js实现圆角的资料
    分享十个应用最广的Javascript框架
    .NET获取ACCESS自动编号列的一种方法(转)
    asp.net 底层资料
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10050186.html
Copyright © 2020-2023  润新知