1. 程式人生 > >初識Leetcode----學習(一)

初識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 {};
    }
};