• 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.

    For example,

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


     1 public class TwoSum {
     2     private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
     3     /** Initialize your data structure here. */
     4     public TwoSum() {
     5         
     6     }
     7     
     8     /** Add the number to an internal data structure.. */
     9     public void add(int number) {
    10         map.put(number, map.containsKey(number) ? map.get(number) + 1 : 1);
    11     }
    12     
    13     /** Find if there exists any pair of numbers which sum is equal to the value. */
    14     public boolean find(int value) {
    15         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    16             int base = entry.getKey();
    17             int findMe = value - base;
    18             
    19             if ((base == findMe && map.get(base) >= 2) || 
    20                  base != findMe && map.containsKey(findMe))
    21                  return true;
    22         }
    23         return false;
    24     }
    25 }
    26 
    27 /**
    28  * Your TwoSum object will be instantiated and called as such:
    29  * TwoSum obj = new TwoSum();
    30  * obj.add(number);
    31  * boolean param_2 = obj.find(value);
    32  */
  • 相关阅读:
    2018年春季个人阅读计划
    软件需求与分析读后感
    假期读后感3
    假期读后感2
    假期读后感1
    四则运算2
    软件工程概论第一次作业
    《大道至简》读后感
    HMX-Server C++ 分步式服务器大版本更新了(有源码)
    HMX-Server-分步式服务器框架(开源+源码)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6395334.html
Copyright © 2020-2023  润新知