zoukankan      html  css  js  c++  java
  • 【LeetCode】170. Two Sum III – Data structure design

    Difficulty:easy

     More:【目录】LeetCode Java实现

    Description

    Design and implement a TwoSum class. It should support the following operations: add
    and find.
    add(input) – Add the number input to an internal data structure.
    find(value) – 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

    Intuition

    add(input): Use HashMap to store the input as key and its count as value

    find(value): similar to Two Sum

    Solution

    import java.util.HashMap;
    import java.util.Map;
    
    public class TwoSum {
    	
    	HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    	
    	public void add(int input) {
    		if (map.containsKey(input)) {
    			map.put(input, map.get(input) + 1);
    		} else
    			map.put(input, 1);
    	}
    
    	public boolean find(int sum) {
    		for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    			if (map.containsKey(sum - entry.getKey())) {
    				if (entry.getKey() == sum - entry.getKey() && entry.getValue() == 1)
    					return false;
    				return true;
    			}
    		}
    		return false;
    	}
    
    	public static void main(String[] args) {
    		TwoSum a = new TwoSum();
    		a.add(2);
    		System.out.println(a.find(4)==false);
    		a.add(2);
    		a.add(6);
    		System.out.println(a.find(4)==true);
    		System.out.println(a.find(12)==false);
    		System.out.println(a.find(8)==true);
    		System.out.println(a.find(2)==false);
    		a.add(10);
    		System.out.println(a.find(12)==true);
    	}
    }
    

      

    true
    true
    true
    true
    true
    true
    TwoSum

    Complexity

    Time complexity :

    For Method add(): O(1) 

    For Method find(): O(n)   (not O(1), because we need to iterate through the hashMap)

    Space complexity : 

    O(n)  for storage

     

    What I've learned

    1. Be aware of the duplicates when writing the method find().

    2. How to iterate through an HashMap? Refer to 遍历HashMap

     More:【目录】LeetCode Java实现

  • 相关阅读:
    [算法题] 汉诺塔问题
    ubuntu导入torch模块报错
    深度问答之提取语料2
    深度问答之提取语料,导入了yml模块
    python读取文件存到excel中
    zipfile.BadZipFile: File is not a zip file
    查看linux系统时间
    tensorflow:typeerror:‘noneType’ object is not callable
    正则匹配中文标点符号
    re.sub用法
  • 原文地址:https://www.cnblogs.com/yongh/p/10009374.html
Copyright © 2011-2022 走看看