Two Sum III - Data structure design

https://oj.leetcode.com/problems/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.

public void add(int number)

public boolean find(int value)


这一题理论上有两种做法add或者find其中一个O(N),剩下的另一个O(1),理论上这两者并不应该有效率上的差距,但是leetcode上find O1, add ON的做法是通不过的,估计应该是test case的问题。能过的就只有find ON和 add O1这种做法。

首先说一下,两种做法都非常依赖HashMap的运用。

先说一下find O1,add ON的做法,维护两个哈希集合HashSet,一个是遇到过的数字set1,另一个是产生过的和set2。

也就是当我们add的时候,遍历set1,然后把所有产生的和都放进set2中,最后再把当前数字放进set1。 当find的时候直接从set2中取出来即可。非常的直观


add O1,find ON的做法其实也是很直观的。本来只需要维护一个哈希set set1,用来放遍历过的数字,然后add的时候直接放数字,find的时候就遍历set1,遍历到一个数字的时候,找value减去这个数字的差是否也在set1里,是的话就表示找到了。但是我们实际上还需要检查一个特殊情况。举个例子,当我们add(1)然后find(2)的时候,应该是找不到的,但根据上述这个做法,当遍历set1到1的时候,2 - 1依旧是1,然后我们又会在set1里找到这个差1。但是我们add(1)两次之后再find(2),应该就是要找的到的。所以我们可以有两种做法,一个把set1变成一个HashMap<Integer, Boolean>, 键放的是add过的数字,值Boolean放的是这个数字是否出现过两次或以上。又或者用一个set2放第二次出现过的数字。这样就可以解决这个问题了。下面给出对应的代码:

    HashSet<Integer> nums = new HashSet<Integer>();
    HashSet<Integer> dups = new HashSet<Integer>();
	public void add(int number) {
	    if(nums.contains(number)){
	        dups.add(number);
	    }else
	        nums.add(number);
	}

	public boolean find(int value) {
	    for(Integer i : nums){
	        if(nums.contains(value - i)){
	            if(value - i == i){
	                if(dups.contains(value - i))
	                    return true;
	            }else
	                return true;
	        }
	    }
	    return false;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值