[LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计

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

Two Sum题的拓展,设计一个数据结构,实现添加数字和找目标数字的功能。用HashMap来存数字和查找。

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class TwoSum {
    private HashMap<Integer, Integer> elements = new HashMap<Integer, Integer>();
  
    public void add(int number) {
        if (elements.containsKey(number)) {
            elements.put(number, elements.get(number) + 1);
        } else {
            elements.put(number, 1);
        }
    }
  
    public boolean find(int value) {
        for (Integer i : elements.keySet()) {
            int target = value - i;
            if (elements.containsKey(target)) {
                if (i == target && elements.get(target) < 2) {
                    continue;
                }
                return true;
            }
        }
        return false;
    }
}

 Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TwoSum(object):
 
    def __init__(self):
        self.dic = {}
 
    def add(self, number):
        if number not in self.dic:
            self.dic[number] = 1
        else:
            self.dic[number] += 1
 
    def find(self, value):
        dic = self.dic
        for num in dic:
            if value - num in dic and (value - num != num or dic[num] > 1):
                return True
        return False

  

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TwoSum(object):
 
    def __init__(self):
        self.lookup = defaultdict(int)
         
    def add(self, number):
        self.lookup[number] += 1
 
    def find(self, value):
        for key in self.lookup:
            num = value - key
            if num in self.lookup and (num != key or self.lookup[key] > 1):
                return True
        return False

 

C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TwoSum {
public:
    void add(int number) {
        ++m[number];
    }
    bool find(int value) {
        for (auto a : m) {
            int t = value - a.first;
            if ((t != a.first && m.count(t)) || (t == a.first && a.second > 1)) {
                return true;
            }
        }
        return false;
    }
private:
    unordered_map<int, int> m;
};

  

相似题目:

[LeetCode] 1. Two Sum 两数和

[LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组

[LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

posted @ 2019-07-06 16:15  天涯海角路  阅读(109)  评论(0)    收藏  举报