Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdeaefd8

Browse files
EASY/src/easy/TwoSumIIIDataStructureDesign.java
1 parent95a44e4 commitdeaefd8

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed
Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,37 @@
11
packageeasy;
22

3-
importjava.util.HashSet;
4-
importjava.util.Set;
3+
importjava.util.ArrayList;
4+
importjava.util.HashMap;
5+
importjava.util.List;
6+
importjava.util.Map;
7+
58

69
//Your TwoSum object will be instantiated and called as such:
710
//TwoSum twoSum = new TwoSum();
811
//twoSum.add(number);
912
//twoSum.find(value);
1013
publicclassTwoSumIIIDataStructureDesign {
11-
privateSet<Integer>set =newHashSet();
14+
privateMap<Integer,Integer>map =newHashMap();
15+
privateList<Integer>list =newArrayList();
1216

1317
// Add the number to an internal data structure.
1418
publicvoidadd(intnumber) {
15-
set.add(number);
19+
list.add(number);
20+
map.put(number,map.getOrDefault(number,0)+1);
1621
}
1722

1823
// Find if there exists any pair of numbers which sum is equal to the value.
1924
publicbooleanfind(intvalue) {
20-
return
25+
for(inti =0;i <list.size();i++){
26+
intval1 =list.get(i);
27+
intval2 =value-val1;
28+
if(map.containsKey(val2)) {
29+
if(val1 ==val2) {
30+
if(map.get(val2) >1)returntrue;
31+
}
32+
elsereturntrue;
33+
}
34+
}
35+
returnfalse;
2136
}
2237
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp