LeetCode OJ : two sum

Two Sum

  Total Accepted: 18444  Total Submissions: 99634 My Submissions

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

思路:先把numbers复制一份出来进行升序排序,利用头尾指正相加和是否等于target来查找,大于的话尾指针向左进一,小于的话头指针向右进一。

代码如下:

class Solution {
public:
	vector<int> twoSum(vector<int> &numbers, int target) 
	{
		// Note: The Solution object is instantiated only once and is reused by each test case.

		vector<int> num = numbers;//复制数据numbers
		sort(num.begin(), num.end());//从大到小排序

		int len = numbers.size();
		int left = 0;
		int right = len - 1;
		int sum = 0;

		vector<int> index;//存储索引

		while(left < right)
		{
			sum = num[left] + num[right];

			if(sum == target)
			{
				for(int i = 0; i < len; ++i)
				{
					if(numbers[i] == num[left])
						index.push_back(i + 1);//下标要加1,因为提取出来的索引不是从0开始的
					else if(numbers[i] == num[right])
						index.push_back(i + 1);
					if(index.size() == 2)//找到两个数就退出
						break;
				}
				break;
			}
			else if(sum > target)//大于target的话就right就往左边,使sum变小;反之~
				--right;
			else
				++left;
		}
		return index;
	}
};

解法2:参考这里(我只是把代码详细注释了一下)。使用HashMap。把每个数都存入map中,任何再逐个遍历,查找是否有 target – nubmers[i]。 时间复杂度 O(n)

代码如下:

vector<int> twoSum(vector<int> &numbers, int target) 
{
	vector<int> res;
	int length = numbers.size();
	map<int,int> mp;  //定义了一个用int作为索引,并拥有相关联的指向int的指针
	for(int i = 0; i < length; ++i)  //关键字是数值,存储的数据是numbers对应的索引
		mp[numbers[i]] = i;
	map<int,int>::iterator it = mp.end();//迭代器指向末尾
	for(int i = 0; i < length; ++i)
	{
		it = mp.find(target - numbers[i]);  //是否能找到target - numbers[i],找到的话返回迭代器指针
		if(it != mp.end())  
		{
			res.push_back(min(i+1,it->second +1));//i是第一个索引,it->second是mp所存储的数据,也就是一个索引值。
			res.push_back(max(i+1,it->second +1));//因为初始值是从1开始的,所以都加上1.
			break;                                //min,max是选择两个之间的最大最小值,因为要按升序输出
		}
	}
	return res;
}


你可能感兴趣的:(LeetCode OJ : two sum)