[Leetcode] 170. 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.

For example,

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

思路

需要考虑的一个特殊情况是:数组中有可能有重复元素,即如果需要查找的值为8,那么可能由4+4构成,这样如果只有一个4是无法构成8的,因此还需要同时考虑每个数组元素出现的次数。在解决的过程中,我们可以根据add优先还是find优先,确定不同的存储结构。

1、add优先:在这种策略中,我们假定add调用的次数要远远多于find调用的次数。所以设计add函数的时间复杂度为O(1),find函数的时间复杂度为O(n)。此时我们哈希nums的值。

2、find优先:在这种策略中,我们假定find调用的次数要远远多于add调用的次数。所以我们设计add函数的时间复杂度是O(n),find函数的时间复杂度是O(1)。此时哈希的是sums的值。需要注意的是,我写的这段代码没有通过所有的测试用例(因为里面的add操作太多了),但是这确实提供了一种在软件设计中trade-off的思考方式。我想如果在面试的过程中能够给面试官展示你这方面的思考和能力,是会有加分的。

代码

1、add优先:

class TwoSum {
public:
    /** Initialize your data structure here. */
    TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    void add(int number) {
        ++hash[number];
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        for (auto val : hash) {
            if (value != 2 * val.first && hash.count(value - val.first)) {
                return true;
            }
            if (value == 2 * val.first && val.second > 1) {
                return true;
            }
        }
        return false;
    }
private:
    unordered_map<int, int> hash;
};

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * bool param_2 = obj.find(value);
 */

2、find优先:

class TwoSum {
public:
    /** Initialize your data structure here. */
    TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    void add(int number) {
        for (int i = 0; i < nums.size(); ++i) {
            sums.insert(nums[i] + number);
        }
        nums.push_back(number);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        return sums.find(value) != sums.end();
    }
private:
    vector<int> nums;
    unordered_set<int> sums;
};

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * bool param_2 = obj.find(value);
 */

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值