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

leetcode——Two Sum 两数之和(AC)

时间:2014-06-09 23:14:45      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:leetcode   two sum   

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

思路为先复制原数据然后进行排序,通过双指针的方式得到两个数的值,然后在原数组中寻找两个数对应的索引位置。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
		if(numbers.empty())
			return result;
		vector<int> temp;
		vector<int>::iterator ite = numbers.begin();
		while(ite<numbers.end())
		{
			temp.push_back(*(ite++));
		}
		sort(temp.begin(),temp.end());
        vector<int>::iterator iteFront = temp.begin();
		vector<int>::iterator iteRear = temp.end()-1;
		int first,second;
		while(iteRear > iteFront)
		{
			if(*iteFront+*iteRear == target)
			{
				for(ite = numbers.begin();ite<numbers.end();ite++)
				{
					if(*ite == *iteFront)
					{
						first = ite-numbers.begin()+1;
						break;
					}
				}
				for(ite = numbers.end()-1; ite>numbers.begin(); ite--)
				{
					if(*ite == *iteRear)
					{
						second = ite-numbers.begin()+1;
						break;
					}
				}
				if(first > second)
				{
					result.push_back(second);
					result.push_back(first);
				}
				else
				{
					result.push_back(first);
					result.push_back(second);
				}
				return result;
			}
			else if(*iteFront+*iteRear < target)
			{
				iteFront++;
			}
			else if(*iteFront+*iteRear > target)
			{
				iteRear--;
			}
		}
}
};


leetcode——Two Sum 两数之和(AC),布布扣,bubuko.com

leetcode——Two Sum 两数之和(AC)

标签:leetcode   two sum   

原文地址:http://blog.csdn.net/dalongyes/article/details/28640175

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