The twosum

在leetcode中刷题遇到了twosum问题
链接(https://leetcode.com/problems/two-sum/description/)
问题描述如下

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

代码如下:

#include<iostream>
using namespace std;
#include<ctime>
#include<random>
#include<vector>
#include<algorithm>
#include<cassert>

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		sort(nums.begin(), nums.end());
		int beg = 0;
		int end = nums.size()-1;
		while (((nums[beg]+nums[end])!=target)&&(nums[beg]!=nums[end]))
		{
			if ((nums[beg] + nums[end]) > target)
				end--;
			else
				beg++;
		}

		vector<int>ret;
		ret.push_back(beg);
		ret.push_back(end);
		return ret;
	}
};

解决思路:
将容器排序,然后用beg,end分别指向容器的开始和结尾,俩项相加与target比较,大则end–,小则beg++,直至beg+end == target 或 beg ==end。然后将beg与end放入容器后返回。

分析:
最坏情况下俩个元素在中间,进行n次比较,时间复杂度为O(n),空间复杂度为O(1)。

注意:
该算法会将容器先排序,又因为引用而改变了原容器的值

一些坑的记录:
1:一开始我将beg及end设为迭代子变量,返回*beg,*end,后来发现这样返回的是值而不是索引。后来改为了int变量

后记:
为了验证这个程序,我又写了一个验证程序。。。。吃饱了撑着了,没办法,代码贴上来,有兴趣的读者可以看看

int main()
{
	vector<int>nums;
	Solution sol;
	int target;
	srand(time(0));
	for (int i = 0; i < 20; i++)
	{
		nums.push_back(rand()%200);
	}
	target = nums[rand() % 20] + nums[rand() % 20];
	cout << "target: " << target << endl;;
	vector<int>ret = sol.twoSum(nums, target);
	for (int i = 0; i < 20; i++)
	{
		cout << nums[i] << " ";
	}
	if (ret[0] != ret[1])
	{
		assert((nums[ret[0]] + nums[ret[1]]) == target);
		cout << endl << ret[0] << ": " << nums[ret[0]] << endl << ret[1] << ":" << nums[ret[1]];
	}
	else
	{
		cout << "unmatch!";
	}

	getchar();

}

猜你喜欢

转载自blog.csdn.net/x676786/article/details/82831048
今日推荐