首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode 170. 两数之和 III - 数据结构设计(哈希map)

LeetCode 170. 两数之和 III - 数据结构设计(哈希map)

作者头像
Michael阿明
发布2020-07-13 15:08:57
发布2020-07-13 15:08:57
6840
举报

1. 题目

设计并实现一个 TwoSum 的类,使该类需要支持 add 和 find 的操作。

add 操作 - 对内部数据结构增加一个数。 find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。

代码语言:javascript
复制
示例 1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false

示例 2:
add(3); add(1); add(2);
find(3) -> true
find(6) -> false

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum-iii-data-structure-design 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
复制
class TwoSum {
	unordered_map<int,int> m;
public:
    /** Initialize your data structure here. */
    TwoSum() {

    }
    
    /** Add the number to an internal data structure.. */
    void add(int number) {
    	m[number]++;
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
    	for(auto it = m.begin(); it != m.end(); ++it)
    	{
    		if((it->first*2 == value && it->second>=2)
    			||(it->first*2 != value && m.find(value-it->first)!=m.end()))
    			return true;
    	}
    	return false;
    }
};

388 ms 22.6 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/02 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 1. 题目
  • 2. 解题
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档