LeetCode170 两数之和 III - 数据结构设计

这篇博客介绍了LeetCode170题的两种解法,包括利用哈希表和排序结合双指针的方法。在哈希表解法中,通过建立映射快速查找目标值。而在排序加双指针的策略中,重点在于确认数据已排序并正确处理is_sorted标志位。

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

LeetCode170 两数之和 III - 数据结构设计

题目

在这里插入图片描述

解题

解题一:哈希表

在这里插入图片描述

// javascript
var TwoSum = function() {
    this.map = new Map();
};

/** 
 * @param {number} number
 * @return {void}
 */
TwoSum.prototype.add = function(number) {
    this.map.set(number, (this.map.get(number) || 0) + 1);
};

/** 
 * @param {number} value
 * @return {boolean}
 */
TwoSum.prototype.find = function(value) {
    for (const x of this.map.keys()) {
        const y = value - x;
        // 如果 x = y 那要保证 x 至少出现了两次
        if (x !== y && this.map.has(y) || x === y && this.map.get(x) > 1) {
            return true;
        }
    }
    return false;
};

在这里插入图片描述

解题二:排序 + 双指针

查找前要确认已经完成排序,特别注意 is_sorted 标志位 的处理。
在这里插入图片描述
在这里插入图片描述

// javascript
TwoSum.prototype.add = function(number) {
    this.nums.push(number);
    this.is_sorted = false;
};

/** 
 * @param {number} value
 * @return {boolean}
 */
TwoSum.prototype.find = function(value) {
    if (this.is_sorted === false) {
        this.nums.sort((a, b) => a - b);
        this.is_sorted = true;
    }
    let low = 0, high = this.nums.length - 1;
    while (low < high) {
        const currSum = this.nums[low] + this.nums[high];
        if (currSum < value) {
            low++;
        } else if (currSum > value) {
            high--;
        } else {
            return true;
        }
    }
    return false;
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值