码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Two Sum III - Data structure design

时间:2016-03-27 07:06:44      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/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

题解:

Two Sum类似.

简历HashMap保存key 和 key的frequency. find value时把HashMap的每一个key当成num1, 来查找HashMap是否有另一个value-num1的key.

num1 = value - num1时,检查num1的frequency是否大于1.

Time Complexity: add O(1). find O(n). Space: O(n).

AC Java:

 1 public class TwoSum {
 2     private HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
 3     // Add the number to an internal data structure.
 4     public void add(int number) {
 5         if(!hm.containsKey(number)){
 6             hm.put(number, 1);
 7         }else{
 8             hm.put(number, hm.get(number)+1);
 9         }
10     }
11 
12     // Find if there exists any pair of numbers which sum is equal to the value.
13     public boolean find(int value) {
14         for(Map.Entry<Integer, Integer> entry : hm.entrySet()){
15             int num1 = entry.getKey();
16             int num2 = value - num1;
17             if(hm.containsKey(num2) && (hm.get(num2) > 1 || num2 != num1)){
18                 return true;
19             }
20         }
21         return false;
22     }
23 }
24 
25 
26 // Your TwoSum object will be instantiated and called as such:
27 // TwoSum twoSum = new TwoSum();
28 // twoSum.add(number);
29 // twoSum.find(value);

 

LeetCode Two Sum III - Data structure design

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5324746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!