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

题目解析:这道题目给了我们一个整数数组,接着给我们一个目标值,如果数组中的两个值相加得到目标值,那么要求我们返回这两个数值的索引值。假设每个目标值只有一种解决方案,同时也不能使用同一个数值两次。

思路:1、可以使用暴力解,利用双重循环来遍历数组去获得结果数组,因为双重循环的时间复杂度为O(n^2),所以超时。

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

2、有一种比较简单的算法, 就是利用c++中Map来查找,先将数组的数值与索引作为map中的键值对存储起来,然后通过map已有的函数find()来查找(target-nums.at(i))的差值。
这种方法是利用空间来换取时间,时间复杂度为O(n)。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        std::map<int,int> vals;
        for(int i=0;i!=nums.size();++i){
            vals.emplace(nums.at(i),i);
        }
        for(int i=0;i!=nums.size();++i)
        {
            const int numToFind=target-nums.at(i);
            auto iter=vals.find(numToFind);
            if(iter!=vals.end()&&i!=iter->second)
            {
                return {i,iter->second};
            }
        }
    }
};

3、与2是同样的原理,只不过利用的是unoredered_map,是无序关联容器,内部采用hash表结构,检索速度更快。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int, int> hash;//无序关联容器,内部采用hash表结构,拥有快速检索的特性
	    vector<int> result;
	for (int i = 0; i < nums.size(); i++) {
		int numberToFind = target - nums[i];
            
            //if numberToFind is found in map, return them
		if (hash.find(numberToFind) != hash.end()) {
                    //+1 because indices are NOT zero based
			result.push_back(hash[numberToFind] );
			result.push_back(i );			
			return result;
		}

            //number was not found. Put it in the map.
		hash[nums[i]] = i;
	}
	return result;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_39116058/article/details/85302867