LeetCode1:Two Sum

1. Two Sum

1.1 description

  • 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].

1.2 暴力解法

直接两层for 循环解决

Cpp Code:

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};
                        }
                }
        }
        return {};
    }
};

时间复杂度O(n2)O(n^2)
LeetCode1:Two Sum

1.3 HashMap

基础知识:
  1. map 学习(下)——C++ 中的 hash_map, unordered_map
  2. std::unordered_map

Cpp Code:

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

时间复杂度O(n)O(n), HashMap以空间换取时间
LeetCode1:Two Sum

慢慢刷题~