Leetcode : Two Sum

来源:互联网 发布:php关联添加元素 编辑:程序博客网 时间:2024/04/27 16:43

Two SumMar 14 '11

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)从头到尾两两相加,很容易解决这个问题,但是需要时间复杂度O(n*n);

2)那有没有更快捷的方法呢,因为我们知道其中一个值A,只需要知道存不存在另外一个值B,使得A+B == target,所以用hash就能很好的解决这个问题


代码如下:

思路1:

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

思路2:

class Solution{public:    vector<int> twoSum(vector<int> &numbers, int target)    {        unordered_map<int,int> nums;        for (size_t i = 1; i < numbers.size(); ++i)            nums[numbers[i]] = i+1;        for (size_t i = 0; i < numbers.size() - 1; ++i)        {            unordered_map<int,int>::iterator it = nums.find(target - numbers[i]);            if (it != nums.end())            {                vector<int> index;                index.push_back(i+1);                index.push_back(it->second);                return index;            }        }    }};