leetcode170. 两数之和 III - 数据结构设计

该博客主要介绍了如何利用哈希表解决LeetCode上的170题,即设计一个数据结构来检查整数流中是否存在两数之和等于特定值。通过创建一个哈希表存储每个数及其出现次数,可以高效地找到和为目标值的数对。Java和Golang的解法分别被展示,强调了哈希表在解决这类问题时的效率优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode170. 两数之和 III - 数据结构设计

题目描述

链接: leetcode170.

设计一个接收整数流的数据结构,该数据结构支持检查是否存在两数之和等于特定值。

实现 TwoSum 类:

TwoSum() 使用空数组初始化 TwoSum 对象
void add(int number) 向数据结构添加一个数 number
boolean find(int value) 寻找数据结构中是否存在一对整数,使得两数之和与给定的值相等。如果存在,返回 true ;否则,返回 false 。

示例:

输入:
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
输出:
[null, null, null, null, true, false]

解释:
TwoSum twoSum = new TwoSum();
twoSum.add(1);   // [] --> [1]
twoSum.add(3);   // [1] --> [1,3]
twoSum.add(5);   // [1,3] --> [1,3,5]
twoSum.find(4);  // 1 + 3 = 4,返回 true
twoSum.find(7);  // 没有两个整数加起来等于 7 ,返回 false

题解

哈希表

  • java解法
class TwoSum {
    Map<Integer, Integer> hashmap;

    /** Initialize your data structure here. */
    public TwoSum() {
        this.hashmap = new HashMap<>();
    }

    /** Add the number to an internal data structure.. */
    public void add(int number) {
        hashmap.put(number, hashmap.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 (Map.Entry<Integer, Integer> integerIntegerEntry : hashmap.entrySet()) {
            Integer temp = integerIntegerEntry.getKey();
            if (hashmap.containsKey(value - temp) && value - temp != temp) {
                return true;
            }
            if (value - temp == temp && hashmap.get(temp) > 1) {
                return true;
            }
        }
        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);
 */
  • golang解法
type TwoSum struct {
	hashMap map[int]int
}


/** Initialize your data structure here. */
func Constructor() TwoSum {
	return TwoSum{
		hashMap: map[int]int{},
	}
}


/** Add the number to an internal data structure.. */
func (this *TwoSum) Add(number int)  {
	this.hashMap[number]++
}


/** Find if there exists any pair of numbers which sum is equal to the value. */
func (this *TwoSum) Find(value int) bool {
	for k, v := range this.hashMap {
		_, ok := this.hashMap[value - k]
		if ok && value - k != k {
			return true
		}
		if value - k == k && v > 1 {
			return true
		}
	}
	return false
}


/**
 * Your TwoSum object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Add(number);
 * param_2 := obj.Find(value);
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值