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.

    For example,

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

    链接: http://leetcode.com/problems/two-sum-iii-data-structure-design/

     2/20/2017, Java

     1 public class TwoSum {
     2     HashMap<Integer, Integer> s = 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         if (s.containsKey(number)) {
    11             s.put(number, s.get(number) + 1);
    12         } else {
    13             s.put(number, 1);
    14         }
    15     }
    16     
    17     /** Find if there exists any pair of numbers which sum is equal to the value. */
    18     public boolean find(int value) {
    19         Integer v;
    20         for(Integer key: s.keySet()) {
    21             v = value - key;
    22             if (v != key && s.containsKey(v)) return true;
    23             if (v == key && s.get(key) > 1) return true;
    24         }
    25         return false;
    26     }
    27 }
    28 
    29 /**
    30  * Your TwoSum object will be instantiated and called as such:
    31  * TwoSum obj = new TwoSum();
    32  * obj.add(number);
    33  * boolean param_2 = obj.find(value);
    34  */
  • 相关阅读:
    jquery收集
    c#语法
    asp.net+MVC
    在线OFFICE方案
    NodeJs中require use get typescript及其他知识点集合
    $.data()
    mongodb 安装、windows服务、创建用户
    Nodejs&Express
    Nodejs + MongoDb
    Nodejs
  • 原文地址:https://www.cnblogs.com/panini/p/6422313.html
Copyright © 2011-2022 走看看