LeetCode(一)Two Sum

博客探讨了LeetCode上的Two Sum问题,介绍了如何找到数组中两个数相加等于目标值的索引。作者首先提到了基础的双层循环解决方案,然后讨论了一种利用大数组和数值作为指针偏移的高效方法,该方法具有优秀的运行时间(8ms),但可能消耗大量空间。文章提出了对于这种以空间换取时间的策略的思考。
摘要由CSDN通过智能技术生成
题目:


Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题目不难理解,都能写的出来,关键看效率,我最先想到的就是俩for循环嵌套,来实现,和大神比简直弱爆了!大神定义一个很长的数组(0Xffff),用数组指针,把数值转换成指针的移位,比如数值是35,那就把数组指针移位35,并赋值为35,用这种方式来构建类似hashMap的功能,效率没的说(leedcode Runtime: 8 ms),但在空间上,可能会浪费不少空间。以空间换时间的做法是否值得,不知是否可取。

入门级:

	vector<int> twoSum1(vector<int>& nums, int target) {//leedcode Runtime: 620 ms
		int temp = 0;
		vector<int> result;
		for (int i = 0; i < nums.size(); i++){
			temp = target - nums[i];
			for (int j = i + 1; j < nums.size(); j++){
				if (temp == nums[j]){
					result.push_back(i + 1);
					result.push_back(j + 1);
				}
			}
		}
		return result;
	}

高手级:

	vector<int> twoSum3(vector<int>& nums, int target) {//leedcode Runtime: 24 ms
		map<int, int> IntHash;
		int temp = 0;
		vector<int> result;
		//for (int i = 0; i < nums.size(); i++)
		//{
		//	IntHash[nums[i]] = i;
		//}
		for (int i = 0; i < nums.size(); i++)
		{
			temp = target - nums[i];
			if (IntHash.find(temp) != IntHash.end()){
				result.push_back(IntHash[temp] + 1);
				result.push_back(i + 1);
				return result;
			}
			else
			{
				IntHash[nums[i]] = i;
			}
		}
		return result;
	}


大神级:

	vector<int> twoSum4(vector<int>& nums, int target) {//leedcode Runtime: 8 ms
		vector<int> result;
		int valueIndices[0Xffff] = { 0 };
		//int valueIndicesN[0xffff] = {0};
		for (size_t i = 0; i != nums.size(); ++i)
		{
			int value = target - nums[i];
			if (valueIndices[value + 0Xffff / 2] != 0)
			{
				result[0] = valueIndices[value + 0Xffff / 2];
				result[1] = i + 1;
				break;
			}
			else
			{
				if (valueIndices[nums[i] + 0Xffff / 2] == 0)
				{
					valueIndices[nums[i] + 0Xffff / 2] = i + 1;
				}
			}

		}
		return result;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值