【LeetCode】1. Two Sum


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

 

首先,不能對該數組作任何預處理。因為要求返回是原始數組的下標,如果對數組進行了排序,那么下標就會亂。

(如果是有序數組,可以用雙指針來做,參見Two Sum II - Input array is sorted

很容易想到用<value, index>的映射表。

遍歷numbers,在映射表中尋找target-numbers[i].

若找到則結束,返回存儲的下標+1和當前下標+1. (注意題目中規定,以1作為起始下標)

若找不到則將<numbers[i], i>加入映射表。

這里又有一個問題,C++中常用的映射表有map, unordered_map。

根據http://www.cplusplus.com/reference/上面的說明我們來比較差異:

map:

Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

map::operator[]:

Logarithmic in size.

unordered_map:

Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

unordered_map::operator[]:

Average case: constant.
Worst case: linear in container size.

本題只需要根據key訪問單個元素,因此unordered_map更合適。

時間復雜度O(n):一次遍歷

空間復雜度O(n):unordered_map

ps: 嚴格來說,target-numbers[i]可能溢出int,因此提升為long long int更魯棒。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> ret(2,-1);
        unordered_map<int, int> m;    //value->index map
        for(int i = 0; i < numbers.size(); i ++)
        {
            if(m.find(target-numbers[i]) == m.end())
            //target-numbers[i] not appeared
                m[numbers[i]] = i;
            else
            {
                ret[0] = m[target-numbers[i]]+1; 
                ret[1] = i+1;
                return ret;
            }
        }
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM