Skip to content

Commit da8c50d

Browse files
committed
premium leetcode
1 parent 3ae1cd3 commit da8c50d

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ This repo contain leetcode solution using DART and GO programming language. Most
6262
- [Excel Sheet Column Title](ExcelSheetColumnTitle/excel_sheet_column_title.dart)
6363
- [Majority Element](MajorityElement/majority_element.dart)
6464
- [The Skyline Problem](TheSkylineProblem/the_skyline_problem.dart)
65+
- [Two Sum III - Data Structure Design](TwoSum-III-DataStructureDesign/two_sum_III_data_structure_design.dart)
6566

6667
## Reach me via
6768

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
3+
-* Two Sum III - Data Structure Design *-
4+
5+
6+
Design and implement a TwoSum class. It should support the following operations:addandfind.
7+
add- Add the number to an internal data structure.
8+
find- Find if there exists any pair of numbers which sum is equal to the value.
9+
Example 1:
10+
add(1); add(3); add(5);
11+
find(4) -> true
12+
find(7) -> false
13+
Example 2:
14+
add(3); add(1); add(2);
15+
find(3) -> true
16+
find(6) -> false
17+
18+
19+
20+
*/
21+
22+
import 'dart:collection';
23+
24+
class A {
25+
/*
26+
27+
Approach 1:
28+
using two hash-set to store unique number and unique sum when add(), add to unique sum and num,
29+
this will have O(n) time for add(), and O(1) for find().
30+
The space complexity though is O(n^2), which unique set for sum will consume O(n^2) space
31+
32+
*/
33+
34+
HashMap<int, int> elements = HashMap<int, int>();
35+
36+
void add(int number) {
37+
if (elements.containsKey(number)) {
38+
elements.forEach((key, value) {
39+
key = number;
40+
value = elements.values.elementAt(number) + 1;
41+
});
42+
} else {
43+
elements.forEach((key, value) {
44+
key = number;
45+
value = 1;
46+
});
47+
}
48+
}
49+
50+
bool find(int value) {
51+
for (int i in elements.keys) {
52+
int target = value - i;
53+
if (elements.containsKey(target)) {
54+
if (i == target && elements.values.elementAt(target) < 2) {
55+
continue;
56+
}
57+
return true;
58+
}
59+
}
60+
return false;
61+
}
62+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package main

TwoSum-III-DataStructureDesign/two_sum_III_data_structure_design.md

Whitespace-only changes.

0 commit comments

Comments
 (0)