/*
170. Two Sum III - Data structure design
https://leetcode.com/problems/two-sum-iii-data-structure-design/
Total Accepted: 10259 Total Submissions: 42707 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) -> true
find(7) -> false
Hide Company Tags LinkedIn
Hide Tags Hash Table Design
Hide Similar Problems (E) Two Sum (E) Unique Word Abbreviation
*/
import java.util.*;
public class TwoSumIII {
private Map<Integer, Integer> table = new HashMap<>();
// add - O(1) runtime, find- O(n) runtime, O(n) space- store in hash table
// Add the number to an internal data structure.
public void add(int number) {
int count = table.containsKey(number) ? table.get(number) : 0;
table.put(number, count + 1);
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
for (Map.Entry<Integer, Integer> entry : table.entrySet()) {
int num = entry.getKey();
int y = value - num;
if ( y == num) {
// For duplicates, ensure there are at least two individual numbers.
if (entry.getValue() >= 2) return true;
} else if (table.containsKey(y)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);
TwoSumIII t = new TwoSumIII();
t.add(1); t.add(3); t.add(5);
System.out.printf("%s \n", t.find(4) == true? "Test case- find(4) success" : "Test case- find(4) failed"); // -> true
System.out.printf("%s \n", t.find(7) == false ? "Test case- find(7) success" : "Test case- find(4) failed"); // -> true// -> false
}
}
170. Two Sum III - Data structure design
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 這個(gè)數(shù)據(jù)結(jié)構(gòu)主要是把數(shù)據(jù)存儲(chǔ)到unordered_multiset里,multiset類似set,但是它允許重復(fù)元...
- Design and implement a TwoSum class. It should support th...
- Design and implement a TwoSum class. It should support th...