Two Sum

最近开始刷leetcode了,感觉和pat相比,这个更看重算法,对时间复杂度的要求更高,而且最关键的是给测试用例,不像PAT上错了就各种猜猜猜,对输出格式也不用这么麻烦。

第一次刷leetcode还是有点不习惯,第一题就纠结了好久。。。

题目要求如下:

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

题目很简单,乍一看直接用2次遍历就可以解决,但是不幸的是会有超时的报错,最后看到题目的tag上又hashtable,所以这还是用STL的MAP来做。

首先遍历数组,将所有的数据都存到MAP中,时间复杂度为O(N)。

然后从前往后扫描数组,对于一个数N,在MAP种找是否target-N也在MAP中,如果在就可以break了。STL的MAP是通过红黑树实现的,查找的时间复杂度为O(logN)。

最后需要注意的是vector的下标是从0开始的,而输出的index是从1开始的。

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        int i,j;
        int n1,n2;
        map<int,int> hash;
        for(i=0;i<numbers.size();i++)
        {
            n1 = numbers[i];
            hash.insert(make_pair(n1,i));
        }
        for(i=0;i<numbers.size();i++)
        {
            n1 = numbers[i];
            n2 = target - n1;
            map<int,int>::iterator iter = hash.find(n2);
            if(iter != hash.end())
            {
                j = iter->second;
                if(i < j)
                {
                    numbers.clear();
                    numbers.push_back(i+1);
                    numbers.push_back(j+1);
                }else if(i > j)
                {
                    numbers.clear();
                    numbers.push_back(j+1);
                    numbers.push_back(i+1);
                }
                else
                    continue;
                break;
            }
        }
        return numbers;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值