首页 > 代码库 > leetcode——Two Sum 两数之和(AC)

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

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--;
			}
		}
}
};