[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
这道题是让我们来设计一个数据结构,而其中两个功能一个是添加元素,一个是找到是否存在其中两个元素的值相加等于给定的target,这道题其实就是two sum的一个变种,我当时做two sum直接用了hashset,然后只需要找是否存在target减去当前值是否存在于hashset中即可。但这道题有些不一样在于可能添加相同的数,这样的情况就会导致,如果一个target是当前数的两倍,如果这个数只出现一次那么肯定返回false,如果出现两次那么就要返回true了,所以我们除了要记录存在哪些值,还需要记录他们出现的次数。这样的话hashmap就成为了我们的首选。和two sum的区别在于需要判断一个条件,即如果某个key值是target的一半,那么检查他出现的次数,如果是两次及以上,返回true,如果只有一次,就返回false
public class TwoSum {
    private HashMap<Integer,Integer> res;
    
    //Initialization
    public TwoSum(){
        res= new HashMap<Integer,Integer>();
    }
    // Add the number to an internal data structure.
	public void add(int number) {
	    if(res.containsKey(number)){
	        int temp = res.get(number);
	        res.put(number,temp+1);
	    }else{
	        res.put(number,1);
	    }
	}

    // Find if there exists any pair of numbers which sum is equal to the value.
	public boolean find(int value) {
	    for(int a:res.keySet()){
	        int temp = value-a;
	        //check whether there exists the difference between target and current value in the map
	        if(res.containsKey(temp)&&temp!=a){
	            return true;
	        }else if(temp==a&&res.get(a)>1){
	            return true;
	        }
	    }
	    return false;
	}
}


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值