170. Two Sum III - Data structure design

题目:

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  */

 

posted @ 2017-02-21 06:17  panini  阅读(164)  评论(0编辑  收藏  举报