[leetCode][012] Two Sum (1)

菜鳥加貝的爬升發表於2015-01-15

【題目】:

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,找出該整型陣列中這樣兩個元素,使得這兩個元素之和等於指定target的值。 題目中假設該兩個元素必然存在,並且是隻有一組(所以相對簡單),返回的是這兩個元素的index值(陣列Index從1開始)。

 

【坑】:

  我們拿到這個題目,首先能夠想到的就是兩次遍歷,但是這樣時間複雜度為O(n^2),無法通過leetCode的OJ測試。所以需要找其他方法。必然要小於O(n^2)複雜度才行。

 

【key point】:

  我們經常會使用空間換取時間的方法來獲取較小的時間複雜度。因此增加必要的資料結構來減少時間複雜度。這道題目一樣,我們增加一個map結構,key為陣列元素值,value為其在陣列中對應的index。每次遍歷到陣列元素便去map結構中查詢對應的補數,如果存在,那就說明找到了。如果沒存在就記錄當前元素以及其index,直到結束。

 

【解答】:

 1 class Solution{
 2 public:
 3      // O(n) runtime, O(n) space
 4     // We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
 5     std::vector<int> twoSum(std::vector<int>& numbers, int target){
 6         std::vector<int> vecRet;
 7         std::map<int, int> mapIndex;
 8         for (size_t i = 0; i < numbers.size(); ++i){
 9             if (0 != mapIndex.count(target - numbers[i])){
10                 int nIndex = mapIndex[target - numbers[i]];
11                 // 當前儲存的Index肯定比i要小,注意要排除i
12                 if (nIndex < i){
13                     vecRet.push_back(nIndex + 1);
14                     vecRet.push_back(i + 1);
15                     return vecRet;
16                 }
17             } else {
18                 mapIndex[numbers[i]] = i;
19             }
20         }
21         return vecRet;
22     } // twoSum
23 };

【leetCode Submission】

【執行結果】:

 

希望各位看官不吝賜教,小弟感恩言謝~

相關文章