leetcode170. 两数之和 III - 数据结构设计

举报
兔老大 发表于 2021/04/28 01:28:05 2021/04/28
【摘要】 设计并实现一个 TwoSum 的类,使该类需要支持 add 和 find 的操作。 add 操作 -  对内部数据结构增加一个数。 find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。 示例 1: add(1); add(3); add(5); find(4)...

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

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

示例 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

在列表有序的情况下,可以使用双指针,时间为O(N),插入一个数字的时间为O(N)。

可以使用哈希表,查找的时间为O(N),插入时间为O(1)。

两种方法空间都是O(N)。

综上所述,没有排序的列表没有必要为了解题去排序。

设计此数据结构时,也是使用哈希表最好。


  
  1. import java.util.HashMap;
  2. class TwoSum {
  3. private HashMap<Integer, Integer> countsMap;
  4. /** Initialize your data structure here. */
  5. public TwoSum() {
  6. countsMap = new HashMap<Integer, Integer>();
  7. }
  8. /** Add the number to an internal data structure.. */
  9. public void add(int number) {
  10. if (countsMap.containsKey(number))
  11. countsMap.replace(number, countsMap.get(number) + 1);
  12. else
  13. countsMap.put(number, 1);
  14. }
  15. /** Find if there exists any pair of numbers which sum is equal to the value. */
  16. public boolean find(int value) {
  17. for (Map.Entry<Integer, Integer> entry : countsMap.entrySet()) {
  18. int key = value - entry.getKey();
  19. if ((key == entry.getKey() && entry.getValue() > 1)
  20. || (key != entry.getKey() && countsMap.containsKey(key))) {
  21. return true;
  22. }
  23. }
  24. return false;
  25. }
  26. }
  27. /**
  28. * Your TwoSum object will be instantiated and called as such:
  29. * TwoSum obj = new TwoSum();
  30. * obj.add(number);
  31. * boolean param_2 = obj.find(value);
  32. */

 

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/104304423

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。