1. 程式人生 > >【LeetCode easy專題】leetcode 1 Two Sum

【LeetCode easy專題】leetcode 1 Two Sum

     題目描述如下:

     此題目比較簡單的一點是給定的測試用例中,一定會有兩個數,使得這個數的和等於給定的target。

     常用的思路是 利用兩個for迴圈遍歷陣列,程式碼如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for(int i = 0; i < nums.size(); i++) {
            for (int j = i + 1 ; j < nums.size(); j++) {
                if (nums[i] + nums[j] == target)
                    return {i,j};
            }
        }       
    }
};

     這種方法思路簡單,耗時較長。常見的改進是利用雜湊表(hash table)。雜湊表是根據(Key)而直接訪問在記憶體儲存位置的資料結構。(來自維基百科) 其常用的儲存方式是陣列+連結串列。在c++中,可以直接呼叫。先給出其基於hash table的程式碼,如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map <int, int> map;
        for (int i = 0; i < nums.size(); i++) {
            map[nums[i]] = i;
        }
        for(int i = 0; i < nums.size(); i++) {
            int left = target - nums[i];
            if(map.count(left) && map[left] != i)
                    return {i,map[left]};     
        }  
    }
};

 在c++標準模板庫中,雜湊表對應的容器是unordered_map,(在標頭檔案 #include <unordered_map>中),其使用方法如下: