【ACWing】75. 和为S的两个数字

题目地址:

https://www.acwing.com/problem/content/71/

输入一个数组和一个数字 s s s,在数组中查找两个数,使得它们的和正好是 s s s。如果有多对数字的和等于 s s s,输出任意一对即可。你可以认为每组输入中都至少含有一组满足条件的输出。

用一个哈希表存之前出现过的数字,遍历到 x x x时,找 s − x s-x sx是否存在即可。代码如下:

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

class Solution {
public:
    vector<int> findNumbersWithSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_set<int> s;
        for (int x : nums) {
            if (s.count(target - x)) {
                res.push_back(target - x);
                res.push_back(x);
                break;
            }
            s.insert(x);
        }

        return res;
    }
};

时空复杂度 O ( n ) O(n) O(n) n n n是数组长度。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值