2019.4.14 LeetCode-Two Sum

LeetCode的两数之和问题要求找到数组中两个数的索引,使其相加等于目标值。本文介绍了三种解决方案:蛮力法,时间复杂度为O(n^2),空间复杂度为O(1);哈希表法,将查找时间从O(n)降低到O(1),但空间复杂度为O(n);以及优化后的哈希表法,避免了返回相同元素的情况,保持了O(n)的时间和空间复杂度。
摘要由CSDN通过智能技术生成

what is “two sum” problem?
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。

solution1: Brute Force蛮力法

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

Time complexity : O(n^2) ,Space complexity : O(1)

solution2:Hash Table哈希表
What is the best way to maintain a mapping of each element in the array to its index? A hash table.哈希表是获取数组中某个指定元素的索引的最好方法。
We reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for speed. 通过增加空间消耗来较少时间消耗。
Beware that the complement must not be nums[i]nums[i] itself!注意获取的另一个元素不能和第一个元素是同一个数。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
{
	map<int, int> m;
	vector<int>res;
	for (int i = 0; i < nums.size(); i++)
	{
		pair<int, int> p(nums[i], i);
		m.insert(p);
	}
	for (int i = 0; i < nums.size(); i++)
	{
		int complement = target - nums[i];
		if (m.count(complement) &&((m.find(complement)->second)!=i))
		{
			res.push_back(i);
			res.push_back((m.find(complement)->second));
            break;
		}
	}
    return res;
}
};

注意:map.count()和map.find()的区别:map.count()是判断hash表中存不存在某个值,如果存在返回1,反之为0。map.find()是返回指向这个值的指针,可以通过指针访问对应的键值。

Time complexity : O(n) ,Space complexity : O(n)

solution3:优化solution2

通过改变给map赋初值的顺序,可以有效回避返回两个元素相同的情况。

class Solution {
public:
   vector<int> twoSum(vector<int>& nums, int target) {
		vector<int>res;
		map<int, int> m;
		for (int i = 0; i < nums.size(); i++)
		{
			int complement = target - nums[i];
			if (m.count(complement))
			{
				res.push_back(m.find(complement)->second);
				res.push_back(i);
				return res;
			}
			pair<int, int> p(nums[i], i);
			m.insert(p);
		}
        return res;
	}
}; 

Time complexity : O(n) ,Space complexity : O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值