[LeetCode] 170. Two Sum III - Data structure design

Two Sum variants, is a design problem. With hashmap exist in Java can be used to help find a list of elements that need faster, JS need not do so.

Analyzing need to remember when num1 + num2 === sum, if num1 === num2, hashmap look inside the num value is greater than 1.

 1 /**
 2  * Initialize your data structure here.
 3  */
 4 var TwoSum = function() {
 5     this.map = {};
 6 };
 7 
 8 /**
 9  * Add the number to an internal data structure..
10  * @param {number} number
11  * @return {void}
12  */
13 TwoSum.prototype.add = function(number) {
14     if (this.map[number]) {
15         this.map[number]++;
16     } else {
17         this.map[number] = 1;
18     }
19 };
20 
21 /**
22  * Find if there exists any pair of numbers which sum is equal to the value.
23  * @param {number} value
24  * @return {boolean}
25  */
26 TwoSum.prototype.find = function(value) {
27     for (var key in this.map) {
28         var num1 = key;
29         var num2 = value - key;
30         if (this.map[num2]) {
31             if (num1 != num2 || this.map[num2] > 1) {
32                 return true;
33             }
34         }
35     }
36     return false;
37 };
38 
39 /**
40  * Your TwoSum object will be instantiated and called as such:
41  * var obj = new TwoSum()
42  * obj.add(number)
43  * var param_2 = obj.find(value)
44  */

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/11639010.html