LeetCode 01 Two Sum

来源:互联网 发布:小企业财务会计软件 编辑:程序博客网 时间:2024/04/30 14:45

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

此题乍一看很简单,只要遍历数组,需找target-numbers[i]的元素即可,算法复杂度为O(n*n),但这样是会超时,不被接受。该方法需要多次扫描数组,而每次扫描的信息又没有被记住,造成信息的浪费。

最好的方法是能够扫描一次,但能够记住每个元素的位置。因此可以使用C++的map类。

第一次扫描,将每个元素及其坐标加入到map中。

第二次扫描,在map中查找target-numbers[i]的元素,要注意target = 2*numbers[i]的情形。map底层是基于红-黑树的,查找复杂度可以认为是O(1)。

这样整个算法的时间复杂度可以认为是O(n).

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> out;        map<int, int> hash_map;        int tmp ;        int index;        size_t  length = numbers.size();        for (int i =0; i<length;  i++) {            //if (!hash_map.count(numbers[i])) {                hash_map.insert(pair<int, int>(numbers[i], i));            //}        }        for (int i =0; i<length;  i++) {            tmp = target - numbers[i];            if (hash_map.count(tmp)) {                 index = hash_map[tmp];                 if(index != i)                {                     out.push_back(index+1);                     out.push_back(i+1);                     return out;                 }             }         }         return out;     }};


1 0