博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Two Sum III - Data Structure Design
阅读量:6632 次
发布时间:2019-06-25

本文共 1624 字,大约阅读时间需要 5 分钟。

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) -> truefind(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
data;17 };

 

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

你可能感兴趣的文章
easyui form validate总是返回false原因
查看>>
在(CListView)列表视图中添加右键菜单的方法
查看>>
解决IE6-IE7下li上下间距
查看>>
聚集索引更新后会不会马上重新排序
查看>>
幸运大抽奖
查看>>
Post请求
查看>>
Java排序算法(三):直接插入排序
查看>>
Python 列表 min() 方法
查看>>
【死磕jeesite源码】Jeesite配置定时任务
查看>>
TBluetoothLEDevice.UpdateOnReconnect
查看>>
poj3517
查看>>
iphone http下载文件
查看>>
poj 1195:Mobile phones(二维树状数组,矩阵求和)
查看>>
Using JRuby with Maven
查看>>
一名女程序员对iOS的想法
查看>>
Spring Websocket实现文本、图片、声音、文件下载及推送、接收及显示(集群模式)...
查看>>
最严新规发布 网络短视频平台该如何降低违规风险? ...
查看>>
云服务器ECS出现速度变慢 以及突然断开怎么办?
查看>>
208亿背后的“秘密”
查看>>
Android系统自带样式(android:theme)解析
查看>>