LeetCode1: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

解题思路:

这道题,很容易想到的就是先排序,在通过两前后指针,向中间靠拢。当两指针所指元素之和与target相等时,则可返回。这里指的注意的是,因为排序后各元素下标会打乱,所以应该构造一个结构体,包含要排序的元素值及最原始的下标。因为要用到排序,所以时间复杂度为O(nlogn)。

第二种思路就是,利用哈希表解决,因为哈希表查找时间复杂度为O(1),当处理一个元素时,判断target-cur是否在哈希表中,在这返回结果即可,这种解法的时间复杂度为O(n)。

实现代码:

#include <iostream>

#include <vector>

#include <unordered_map>

using namespace std;



/**

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



*/

class Solution {

public:

    vector<int> twoSum(vector<int> &numbers, int target) {

        vector<int> resvec(2, 0);

        if(numbers.empty())

            return resvec;

        unordered_map<int, int> imap;

        int len = numbers.size();

//        for(int i = 0; i < len; i++)

//            imap[numbers[i]] = i+1;

        for(int i = 0; i < len; i++)

        {

            //这里要注意,一开始,我直接利用数组元素初始化map,但会出现相同元素值覆盖的情况 

            if(imap.count(target - numbers[i]))

            {

                resvec[0] = imap[target - numbers[i]] + 1;

                resvec[1] = i+1;               

                break;

            }

            imap[numbers[i]] = i;

                        

        }



        return resvec;

      

    }

};

int main(void)

{

    int arr[] = {2,7,11,15};

    vector<int> numbers(arr, arr+4);

    Solution solution;

    vector<int> resvec = solution.twoSum(numbers, 9);

    

    vector<int>::iterator iter;

    for(iter = resvec.begin(); iter != resvec.end(); ++iter)

        cout<<*iter<<endl;

    

    return 0;

}

你可能感兴趣的:(LeetCode)