初识Leetcode----学习(一)

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

暴力解题:时间复杂度O(n^2)

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

看了大佬的解题思路,也理解了更为简单的解题方法:时间复杂度为O(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int,int> mp;     //要保存数组的值-下标,值可能是无序的,所以采用unordered_map
        vector<int> vec;
        for (int i = 0;i < nums.size(); ++i)
        {
            mp[nums[i]] = i;    //用给定数据初始化map
        }
        for (int i = 0;i < nums.size(); ++i)
        {
            int t = target - nums[i];      //nums[i]为第一个数,t得到第二个数
            if (mp.count(t) && mp[t] != i) //判断t是否符合要求
            {
                vec.push_back(i);          //将所得两个数的下标存入目标容器
                vec.push_back(mp[t]);
                break;           //如找到则退出搜索
            }
        }
        return vec;           //返回所得结果
    }
};

更为简洁的方案:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int,int> mp;
        for (int i = 0;i < nums.size();++i)
        {
            if (mp.count(target - nums[i]))
            {
                return {mp[target - nums[i]], i}; //由于省去了单独的初始化过程,在这里要特别注意,这里是找到第二个数之后回去找到第一个数的结果,因此i代表第二个数的下标
            }
             mp[nums[i]] = i;
        }
        return {};
    }
};

猜你喜欢

转载自blog.csdn.net/qq_38790716/article/details/82945738