LeetCode1:Two Sum

mickole發表於2014-04-28

題目:

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;
}

相關文章