两数之和

leetcode-两数之和

Posted by Fans on September 14, 2021

题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

暴力解法

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #暴力法
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[j]+nums[i]==target:
                    return [i,j]

时间复杂度On,空间复杂度O1

c++版本:

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

哈希表解法

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[nums[i]] = i
        return []

时间复杂度On,空间复杂度On

利用字典提前存储已经访问过的数据

C++版本:

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

        vector<int> res;
        unordered_map<int, int> hashtable;
        for(int i=0;i<nums.size();i++)
        {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) 
            {
                res.push_back(it->second);
                res.push_back(i);
                return res;
            }
            hashtable[nums[i]] = i;
            
        }
        return res;
    }
};