Two Sums

Problem

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.ios

Example

Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].spa

解題思路

在給出的列表找查找是否存在一個數,知足:target-nums[1]。實際上還有個相似的題目,叫three sums。只是兩個數變成了三個數,解決思路相似。code

My Solution

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> result;
		for (int i = 0; i != nums.size(); i++)
		{
			for (int j = i + 1; j != nums.size(); j++)
			{
				if ((target - nums[i]) == nums[j])
				{
					result.push_back(i);
					result.push_back(j);
				}
			}
		}
		return result;
	}
};

The code on VS2013:

#include<iostream>
#include<stdlib.h>
#include<algorithm>
#include<vector>

using namespace std;

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> result;
		for (int i = 0; i != nums.size(); i++)
		{
			for (int j = i + 1; j != nums.size(); j++)
			{
				if ((target - nums[i]) == nums[j])
				{
					result.push_back(i);
					result.push_back(j);
				}
				else
					cout << i <<" "<<"and"<<" "<< j <<" "<< "both are not the targets!" << endl;
			}

		}
		cout << "Here are the correct numbers:" << endl;
		for (int i = 0; i < result.size(); i++)
		{
			cout << result[i] << endl;
		}
		return result;
	}
};
int main(void)
{
	Solution s;
	vector<int> test;
	test.push_back(3);
	test.push_back(2);
	test.push_back(4);

	vector<int>::iterator it;
	cout << "Here are test array:" << endl;
	for (it = test.begin(); it != test.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	s.twoSum(test,6);
	system("pause");
	return 0;
}
相關文章
相關標籤/搜索