Two Sum III - Data structure design

来源:互联网 发布:中国mysql用户组 编辑:程序博客网 时间:2024/06/05 07:00

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