奔跑的小河
Talk is cheap. Show me the code.

导航

 

描述:

       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

分析:

        给定一个整型数组和一个目标值(targe),找出数组中两个值的和等于目标值(targe),然后返回下标,下标1要小于小标2 并且下标不是以0开始的。假设输入严格保证只有一个解决答案。这里有三种解决方案,第一种想法就是暴力求解,这里为了学号STL也是用两种方式解答。第二种,查看网上大神的解法是利用hash的高效查找来实现,看了涨姿势啊!第三种是稍微动动脑筋就可以想出来的,先用算法中的sort排序,再将下标和对应的值放入hash中,然后二分查找到比target小的部分,然后左右夹逼,若相加大于target,右边指针左移一位,若小右移一位。

代码:

直接复制到VS中即可。

#include "stdafx.h"
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;

class Solution{
public:
	//暴力求解
	vector<int> TwoSum(vector<int> &num, int target){
		vector<int>::const_iterator num_Iter1;
		vector<int>::const_iterator num_Iter2;
		int i=1,j=2;
		vector<int> vRtn;
		for (num_Iter1 = num.cbegin();num_Iter1 != num.cend();++num_Iter1){
			for (num_Iter2 = num_Iter1 + 1;num_Iter2 != num.cend();++num_Iter2){
				if (*num_Iter1 + *num_Iter2 == target){					
					vRtn.push_back(i);
					vRtn.push_back(j);
					break;
				}
				j++;
			}
			i++;
			j = i+1;
		}
		return vRtn;
	}

	vector<int> TwoSum1(vector<int> &num, int target){
		int i,j;
		vector<int> vRtn;
		for(i=0;i < num.size();++i){
			for(j=i+1;j < num.size();++j){
				if (num.at(i)+ num.at(j) == target){
					vRtn.push_back(i+1);
					vRtn.push_back(j+1);
					break;
				}
			}
		}
		return vRtn;
	}

	//高效解法O(n),用一个哈希表,存储每个数对应的下标,利用hash的高效查找。
	vector<int> TwoSum2(vector<int> &num, int target){
		unordered_map<int, int> unmap;
		vector<int> vRtn;
		//先将位置存起来
		for (int i=0;i< num.size();++i){
			unmap[num[i]] = i;
		}
		int gap;
		for (int i=0;i< num.size();++i){
			gap = target - num[i];
			if (unmap.find(gap) != unmap.end() && unmap[gap]>i){
				vRtn.push_back(i+1);
				vRtn.push_back(unmap[gap] + 1);
				break;
			}
		}
		return vRtn;
	}

};

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> v1,v2;
	v1.push_back(2);
	v1.push_back(7);
	v1.push_back(9);
	v1.push_back(11);
	v1.push_back(32);
	v1.push_back(43);

	Solution s;
	v2 = s.TwoSum2(v1,9);
	vector <int>::iterator v2_Iter;
	cout << "v2 =" ;
	for ( v2_Iter = v2.begin( ) ; v2_Iter != v2.end( ) ; v2_Iter++ )
		cout << " " << *v2_Iter;
	cout << endl;


	system("pause");
	return 0;
}



 

posted on 2015-05-30 16:33  奔跑的小河  阅读(117)  评论(0编辑  收藏  举报