[LeetCode] Two Sum III - Data Structure Design

本文介绍如何设计并实现一个TwoSum类,该类支持添加整数和查找特定数值是否存在两个整数之和等于目标值。通过使用unordered_map数据结构,实现高效的查找操作。

Problem Description:

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

Well, the basic idea is simple: just store the added numbers in an internal data structure. When we are asked to find a value, we just iterate over all the numbers in the internal data structure. For each number num, if value - num is also in the data structurue and not at the same "position" as num, then return true. After iterating over all num and we have not returnred true, return false.

The key to an efficient implementation lies in what data structure to store the added numbers. Since there may be duplicate numbers, personally I think using an unordered_map is a nice choice. It uses num as key and its number of appearances as value. It enalbes both O(1) insertion and O(1) query, and thus O(1) for add and O(n) for find if there are n elements in total.

The code is as follows.

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

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4554395.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值