leetcode--P1 Two Sum

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


作为第一题本来以为能够在凌晨轻松A过,但还是too young了。


一开始的思路,最简单直接使用O(N^2)的暴力搜索,看有没有两个数加起来与target相等,代码如下:


<span style="font-size:14px;">int* twoSum(int* x, int n, int tag) {
    int i,j,index[2];
    for(i=0;i<n;i++)
     for(j=i+1;j<n;j++)
    {
        if(x[i]+x[j]==tag)
        {
            index[0]=i+1;
            index[1]=j+1;
        }
    }
    return index;
}</span>

很明显,这样会TLE,所以没办法只能想着用hash来做,但由于在写题时没有用C++的习惯,导致直接使用一个数组来模拟hash,然后发现测试数据中存在需要索引为负数的数据。无奈,只能使用C++了。

通过C++中的map或hash_map存储这张表,完成常数级别的搜索,此题AC,代码如下:

<span style="font-size:14px;">class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int tag) {
        map<int,int> f;
        vector<int> index;
        int n=0;
        vector<int>::iterator iter;
        for( iter = nums.begin(); iter != nums.end(); iter++ )
        {
            n++;
        }
        for(int i=0;i<n;i++)
        {
            map<int,int>::iterator l_it;
            int k;
            l_it=f.find(nums[i]);
            if(l_it==f.end()) f.insert(pair<int,int>(nums[i],i));
            l_it=f.find(tag-nums[i]);
            if(l_it!=f.end())
            {
                k=l_it->second;
                if(k<i)
                {
                index.push_back(k+1);
                index.push_back(i+1);
                }
            }
        }
        return index;
    }
};</span>

由于没有任何优化手段,运行时间为56ms,在所有A过的C++代码中处于比较差的。

其中有一点,由于长久未使用迭代器iterator,此处记下,通过pair添加进去的数据,调用迭代器指针时,使用l->first和l->second进行对数据的访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值