/*
Date: March 21, 2016
170. Two Sum III - Data structure design
[My Submissions](https://leetcode.com/problems/two-sum-iii-data-structure-design/submissions/)Question
Total Accepted: **10075** Total Submissions: **41802** Difficulty: **Easy**
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) -> truefind(7) -> false
Hide Company Tags
[LinkedIn](https://leetcode.com/company/linkedin/)
Hide Tags
[Hash Table](https://leetcode.com/tag/hash-table/) [Design](https://leetcode.com/tag/design/)
Hide Similar Problems
[(E) Two Sum](https://leetcode.com/problems/two-sum/) [(E) Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/)
*/
import java.util.*;
public class TwoSumDataStructure {
// add O(1) time, find(value) O(n) time, space O(n)
public static void main(String args[]) {
TwoSumDataStructure twoSum = new TwoSumDataStructure();
twoSum.add(1); twoSum.add(3); twoSum.add(5);
System.out.printf(" find(4) = %b\n", twoSum.find(4));
System.out.printf(" find(7) = %b\n", twoSum.find(7));
}
private static HashMap<Integer, Integer> map = new HashMap<>();
public static void add(int input) {
int count = map.containsKey(input) ? map.get(input) : 0;
map.put(input, count + 1);
}
public static boolean find(int val) {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int num = entry.getKey();
int y = val - num;
if (y == num) {
// For dumplicates, ensure there are at least two individual numbers.
if (entry.getValue() >= 2) return true;
} else if (map.containsKey(y)) {
return true;
}
}
return false;
}
}
170. Two Sum III - Data structure design
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 这个数据结构主要是把数据存储到unordered_multiset里,multiset类似set,但是它允许重复元...
- Design and implement a TwoSum class. It should support th...
- Design and implement a TwoSum class. It should support th...