Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

170. Two Sum III - Data structure design

Posted on 2020-05-15 | Edited on 2021-01-22

https://leetcode.com/problems/two-sum-iii-data-structure-design/

HashTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class TwoSum {

HashMap<Integer,Integer> map;
/** Initialize your data structure here. */
public TwoSum() {
map=new HashMap<>();
}

/** Add the number to an internal data structure.. */
public void add(int number) {
if(this.map.containsKey(number)) map.replace(number,map.get(number)+1);
else map.put(number,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:map.entrySet()){
int complement=value-entry.getKey();
if(complement!=entry.getKey()){
if(map.containsKey(complement)) return true;
}else{
if(map.get(complement)>1) return true;
}
}
return false;
}
}

/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/

<1…201202203…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%