码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode之Two Sum

时间:2014-11-07 11:18:43      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:leetcode   two sum   vector   

题目:

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

题意分析:

给定的是一个未排序的vector整形数组和一个target,题中的排好序的数组只是一个特例。

要求在数组中找出两个数,其和等于target,且说明了这样的数字有且只有一对,所以此处不考虑找不到的情况。

也可考虑vector和multimap结合的方式。

此处排序耗费nlogn,查找耗费n,两次下标查找耗费n,总的时间复杂度为nlogn。

  1. 本题首先将原数组备份,其实就是存放好各个数字的原始位置。
  2. 将数组进行排序,然后从两头往中间靠拢,直到找到符合要求的整数对。
  3. 在备份数组中搜索这两个整数所在的位置,保存到返回结果中。

代码:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

class Solution {
public:
	vector<int> twoSum(vector<int> &numbers, int target) 
	{
		int vecSize = numbers.size();
		int nStart = 0;                    //搜索的起始位置
		int nTail = vecSize-1;
		vector<int> findLoc(numbers);     //为保存原来的数组顺序
		vector<int> VerRes;               //保存返回的下标结果

		sort(numbers.begin(),numbers.end());      //先进行排序,可进行一趟搜索
		while (nStart <= nTail)
		{
			if (numbers[nStart] + numbers[nTail] < target)
			{
				nStart++;
			}
			else if (numbers[nStart] + numbers[nTail] >target)
			{
				nTail--;
			}
			else if (numbers[nStart] + numbers[nTail] == target)   //记录结果数据对在原来的vector中的位置
			{
				for (int i = 0; i< vecSize; i++)
				{
					if (numbers[nStart] == findLoc[i]  )           //查找符合要求的数字在原数组中的下标
					{
						VerRes.push_back(i+1);
						break;
					}
				}
				for (int i = 0; i< vecSize; i++)
				{
					if (numbers[nTail] == findLoc[i]  && (i+1) != VerRes[0])
					{
						VerRes.push_back(i+1);
						break;
					}
				}
				break;
			} 
		}
		sort(VerRes.begin(),VerRes.end());
		return VerRes;
	}
};


int main()
{
	vector<int> num;
	vector<int> res;
	num.push_back(0);
	num.push_back(2);
	num.push_back(4);
	num.push_back(0);
	int target = 0;

	res =  Solution().twoSum(num, target);
	for (int i=0; i<res.size(); i++)
	{
		cout<<res[i]<<" ";
	}
	cout<<endl;
	system("pause");

}

bubuko.com,布布扣


LeetCode之Two Sum

标签:leetcode   two sum   vector   

原文地址:http://blog.csdn.net/firechungelaile/article/details/40889379

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!