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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章