leetcode--Two Sum

本文介绍了一种使用哈希表快速解决数组中寻找两数之和等于特定目标值的问题的方法,包括特殊情况处理及代码实现。

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

1.题目描述

Given an array of integers, find two numbers such that they add up to a specific target number.
 
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
 
You may assume that each input would have exactly one solution.
 
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

1.解法分析

由于题目说得很明白,一定有解且解只有一组,那么这题用hash做自然是最快了,但是对于偶数输入,比如target为8,如果结果是4和4的相加需要特殊考虑。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        unordered_set<int> myHash;
        vector<int>::iterator iter;
        vector<int> result;
        result.assign(2,0);
        
        if(target%2==0)
        {
            int count=0;
            for(int i=0;i<numbers.size();++i)
            {
                if(numbers[i]==target/2)
                {
                    if(count==0){result[0]=i+1;count++;}
                    else {result[1]=i+1;return result;}
                }
            }
        }
        
        for(iter=numbers.begin();iter!=numbers.end();++iter)
        {
            myHash.insert(*iter);
        }
        
 
        
        for(int i=0;i<numbers.size();++i)
        {
            myHash.erase(numbers[i]);
            if(myHash.count(target-numbers[i])==1)
            {
                result[0]=i+1;break;
            }
            myHash.insert(numbers[i]);
        }
        
        for(int i=result[0];i<numbers.size();++i)
        {
            if((numbers[result[0]-1]+numbers[i])==target)
            {
                result[1]=i+1;break;
            }
        }
        
        return result;
        
        
        
    }
};

转载于:https://www.cnblogs.com/obama/p/3266680.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值