[LeetCode]1 两者之和

本文介绍了一个经典的编程面试题目——TwoSum问题,即在一个整数数组中寻找两个数,使它们的和等于特定的目标值,并返回这两个数的下标。文章提供了两种解决方案:一种是简单的双循环遍历,另一种是高效的哈希表查找。

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

Two Sum(两者之和)

【难度:Easy】
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给定一整数数组,返回其中两个数相加之和为目标值的下标,假设有且只有1个解。


解题思路

最直接的方法是通过两趟循环来遍历所有可能性,来找到符合要求的下标。但是这种方法虽然能过,耗时却比较大。因此可以考虑使用哈希的方法,将整数与其下标绑定,利用map的性质,达到一趟循环解决的目的。


c++代码如下:
简单方法:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        if (nums.empty())
            return ans;
        for (int i = 0; i < nums.size(); i++) {
            ans.push_back(i);
            for (int j = i+1; j < nums.size(); j++) {
                if (nums[i]+nums[j] == target) {
                    ans.push_back(j);
                    return ans;
                }
            }
            ans.pop_back();
        }
        return ans;
    }
};

使用map:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        if (nums.empty())
            return ans;
        map<int,int> m;
        for (int i = 0; i < nums.size(); i++) {
            if (m.find(target-nums[i]) != m.end()) {
                ans.push_back(m[target-nums[i]]);
                ans.push_back(i);
                return ans;
            }
            m[nums[i]] = i;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值