兩數之和題解(暴力、哈希表)

解題思路

暴力枚舉

暴力枚舉的方法:使用兩重循環枚舉下標i,j,然後判斷是否滿足條件,適當的優化減少循環,複雜度O(n ^ 2);

代碼

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

        return res; 
    }        
};

C++哈希表方法

循環nums數組:
1、判斷target - nums[i]是否在哈希表中,若在,加入到res中;
2、將nums[i] 插入哈希表中,返回下標;
分析:當循環到時,nums[i]一定在哈希表中,且存在nums[i] + nums[j] == target,一定可以找到一組解,並且數據保證只有一組解,複雜度爲O(n),因爲只掃描了一遍,並且哈希表的插入和刪除操作複雜度爲O(1);

代碼

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> hash;

        for(int i = 0; i < nums.size(); i ++ )
        {
           int another = target - nums[i];
           if(hash.count(another))
           {
               res = vector<int> ({hash[another], i});
               break;
           }
           hash[nums[i]] = i;
        }

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