Leetcode 170. Two Sum III - Data structure design

在这里插入图片描述
方法1: 这道题目其实和two sum基本一样。这道题目难点就在于找到两个数的sum为一个给定的值。方法1我们用sorted list & two pointers来做。时间复杂nlogn,空间复杂n。具体思路参考lc官方解答1.

class TwoSum {
    List<Integer> list = new ArrayList<>();
    boolean is_sorted = false;
    /** Initialize your data structure here. */
    public TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        list.add(number);
        is_sorted = false;
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        if(!is_sorted){
           Collections.sort(list); 
        }
        int low = 0;
        int high = list.size() - 1;
        while(low < high){
            int sum = list.get(low) + list.get(high);
            if( sum == value) return true;
            else if(sum > value) high--;
            else low++;
        }
        return false;
    }
}

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

方法2: hashtable。这也是解决two sum的一个好办法,不过时间复杂变为n,空间复杂n,空间复杂n。

class TwoSum {
    Map<Integer, Integer> map = new HashMap<>();
    /** Initialize your data structure here. */
    public TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        map.put(number, map.getOrDefault(number, 0) + 1);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for(int num : map.keySet()){
            map.put(num, map.get(num) - 1);
            int remain = value - num;
            if(map.keySet().contains(remain) && map.get(remain) >= 1){
                map.put(num, map.get(num) + 1);
                return true;
            }   
            map.put(num, map.get(num) + 1);
        }
        return false;
    }
}

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

总结:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值