LeetCode之1_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

題意分析:

給定的是一個未排序的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");

}



發佈了61 篇原創文章 · 獲贊 20 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章