1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution 1:

使用暴力破解方法,先循环数组中的元素,针对每一个元素,再次遍历数组,查看数组中是否含有响应的补元素,一次算法复杂度为O(n2),C++代码如下:

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

Solution2:

         我们在第二个循环中遍历所有的元素来查找是否有component,这个循环的复杂度为O(n),如果我们有办法将该查找的复杂度变为O(1),则整个算法的复杂度将会变为O(1),因此我们采用哈希表(hashmap)来存储元素,进行查找,hashmap的平均查找时间为O(1)。此算法的空间复杂度为O(n),时间复杂度为O(n),C++代码如下所示:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> namemap;
        vector<int> index;
        for (int i = 0; i < nums.size(); i++){
            if (namemap.find(target - nums[i]) != namemap.end()){  //在map中存在匹配的元素
                index.push_back(namemap[target - nums[i]]);
                index.push_back(i);
                return index;
            }
            namemap[nums[i]] = i;
        }
    }
};
 
原文地址:https://www.cnblogs.com/Lxiaoyouling/p/8037993.html