C++实现LeetCode(170.两数之和之三(?,数据结构设计))

这篇文章主要介绍了C++实现LeetCode(170.两数之和之三 – 数据结构设计),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

C++实现LeetCode(170.两数之和之三,?,数据结构设计),久久派带你了解更多相关信息。

[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.

Example 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Example 2:

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

这道题让我们设计一个 Two Sum 的数据结构,跟 LeetCode 的第一道题 Two Sum 没有什么太大的区别,作为 LeetCode 的首题,Two Sum 的名气不小啊,正所谓平生不会 TwoSum,刷尽 LeetCode 也枉然。记得原来在背单词的时候,总是记得第一个单词是 abandon,结果有些人背来背去还在 abandon,有时候想想刷题其实跟背 GRE 红宝书没啥太大的区别,都是一个熟练功夫,并不需要有多高的天赋,只要下足功夫,都能达到一个很不错的水平,套用一句鸡汤问来激励下吧,“有些时候我们的努力程度根本达不到需要拼天赋的地步”,好了,不闲扯了,来看题吧。不过这题也没啥可讲的,会做 Two Sum 的这题就很简单了,先来看用 HashMap 的解法,把每个数字和其出现的次数建立映射,然后遍历 HashMap,对于每个值,先求出此值和目标值之间的差值t,然后需要分两种情况来看,如果当前值不等于差值t,那么只要 HashMap 中有差值t就返回 True,或者是当差值t等于当前值时,如果此时 HashMap 的映射次数大于1,则表示 HashMap 中还有另一个和当前值相等的数字,二者相加就是目标值,参见代码如下:

解法一:

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;};

另一种解法不用 HashMap,而是 unordered_multiset 来做,但是原理和上面一样,参见代码如下:

解法二:

class TwoSum {public:    void add(int number) {        s.insert(number);    }    bool find(int value) {        for (auto a : s) {            int cnt = a == value - a ? 1 : 0;            if (s.count(value - a) > cnt) {                return true;            }        }        return false;    }private:    unordered_multiset<int> s;};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/170

类似题目:

Two Sum

Unique Word Abbreviation

Two Sum IV – Input is a BST

参考资料:

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

https://www.zzm8.com/d/file/p/2021080218003213609/2021080218003213610

https://www.zzm8.com/d/file/p/2021080218003313619/2021080218003313620

到此这篇关于C++实现LeetCode(170.两数之和之三 – 数据结构设计)的文章就介绍到这了,更多相关C++实现两数之和之三 – 数据结构设计内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/8997.html

(0)
nan
上一篇 2021-08-02
下一篇 2021-08-02

相关推荐

发表回复

登录后才能评论