【leetcode】 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


解決方案1:排序完從兩端開始夾逼,時間複雜度O(nlogn)。排序O(nlogn), 查找O(n).但是結果必須輸出index,所以此方案不成立

解決方案2:窮舉遍歷,時間複雜度O(n2)

解決方案3:用哈希表存儲,然後遍歷

因爲unordered_map的查找時間複雜度爲O(logn),所以此算法時間複雜度爲O(nlogn)

//解決方案3
class Solution {
public:
    vector<int> twoSum(vector<int>& num, int target) {
        unordered_map <int, int> mapping;
        vector <int> result;
        
        for (int i = 0; i < num.size(); ++i) {
            mapping[num[i]] = i;
        }
        
        for (int i = 0; i < num.size(); ++i) {
            const int cmp = target - num[i];
            
            //find(key)
            //如果mapping.find() == mapping.end() 則說明未找到
            if (mapping.find(cmp) != mapping.end() && mapping[cmp] > i) {
                result.push_back(i + 1);
                result.push_back(mapping[cmp] + 1);
                break;
            }
        }
        
        return result;
    }
};

解決方案4:假設輸入的值範圍在-/+ 40000,可以用如下方法解決

以空間換時間的方式。時間複雜度O(n)

//解決方案4

class Solution {
 public:
 vector<int> twoSum(vector<int>& nums, int target) {
    vector<int>ans;
    int tmp[80000]={0};
    for(int i=0;i<nums.size();i++)
           tmp[40000+nums[i]]=i+1;
    for(int i=0;i<nums.size();i++)
           if(tmp[40000+target-nums[i]]&&tmp[40000+target-nums[i]]!=i+1)
           {
               ans.push_back(i+1);
               ans.push_back(tmp[40000+target-nums[i]]);
               return ans;
           }
 }
};

解決方案4屬於投機取巧的方法,不過在我之前面試時碰到的一個題目是給定範圍讓你排序或者查找個數,其實也可以利用到解決方案4的方法。

引用:

https://github.com/soulmachine/leetcode 

https://leetcode.com/discuss/57223/my-code-beats-99%25-8ms-using-c


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章