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

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

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
1 public class TwoSum { 2     private HashMap
map = new HashMap
(); 3 /** Initialize your data structure here. */ 4 public TwoSum() { 5 6 } 7 8 /** Add the number to an internal data structure.. */ 9 public void add(int number) {10 map.put(number, map.containsKey(number) ? map.get(number) + 1 : 1);11 }12 13 /** Find if there exists any pair of numbers which sum is equal to the value. */14 public boolean find(int value) {15 for (Map.Entry
entry : map.entrySet()) {16 int base = entry.getKey();17 int findMe = value - base;18 19 if ((base == findMe && map.get(base) >= 2) || 20 base != findMe && map.containsKey(findMe))21 return true;22 }23 return false;24 }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 */

 

转载于:https://www.cnblogs.com/amazingzoe/p/6395334.html

你可能感兴趣的文章
cnblog!i'm coming!
查看>>
使用点符号代替溢出的文本
查看>>
Axios 中文说明
查看>>
fatal: remote origin already exists.
查看>>
gridview 自定义value值
查看>>
2018二月实现计划成果及其三月规划
查看>>
类名.class和getClass()区别
查看>>
12/17面试题
查看>>
LeetCode 242. Valid Anagram
查看>>
JSP表单提交乱码
查看>>
如何适应现代雇佣关系
查看>>
团队项目(第五周)
查看>>
SQL 优化经验总结34条
查看>>
开源 视频会议 收藏
查看>>
核心J2EE模式 - 截取过滤器
查看>>
.net开源CMS
查看>>
JdbcTemplate
查看>>
第一次使用maven记录
查看>>
SharePoint服务器端对象模型 之 使用CAML进展数据查询
查看>>
Building Tablet PC Applications ROB JARRETT
查看>>