【LeetCode】Two Sum (C++)

本文介绍了一种使用C++解决LeetCode经典题目“两数之和”的高效方法,并对比了C语言实现。C++解决方案采用了哈希表思想,显著提高了查找速度。

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

最近花了点时间了解了下C++,感觉与C还是有很多不同的。接下来坚持每天用C++写五道LeetCode。fighting!

题目:

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


代码:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n=nums.size();
        vector<int> ans;
        map<int,int> m;
        for(int i=0; i<n; i++)
            m[nums[i]]=i;
        for(int i=0; i<n; i++){
            int t=target-nums[i];
            if(m.count(t)&&m[t]!=i){
                ans.push_back(i);
                ans.push_back(m[t]);
                break;
            }
        }
        return ans;
    }
};

这个代码10ms通过了。

下面这个是之前写的C,就是两重循环,比较基础,运行了76ms。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int i,j;
    int* a=(int*)malloc(2*sizeof(int));
    for(i=0;i<numsSize;i++)
    {
        for(j=i+1;j<numsSize;j++)
        {
            if(nums[i]+nums[j]==target)
            {
                a[0]=i;
                a[1]=j;
            }
        }
    }
    return a;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值