"Leetcode" two Sum

Source: Internet
Author: User

Twosum

Given an array of Integers,find two numbers such this they add up to a specific target number.

The function two Sum should return indices of the two numbers such this they add up to the Target,where index1 is Les S than Index2.

Please note this your returned answers (both INDEX1 and index2) are not zero-based.

You may assume this each input would have exactly one solution.

Input:numbers={2, 7, one, target=9

Output:index1=1, index2=2


Method One:

Brute Force solution
class Solution1
{public
: 
	vector<int> twosum (vector<int> &num, int target)
	{
		vector<int> rs;

		for (int i = 0; i < num.size (); ++i)
		{for
			(int j = i + 1; j < Num.size (); j + +)
			{
				if (Num[i] + num[ J] = = target)
				{
					Rs.push_back (i + 1);
					Rs.push_back (j + 1);
					return RS;
				}
			}
		return RS;
	}
;

Method Two:

With a hash table, store each number corresponding to the subscript
class Solution2
{public
:
	vector<int> twosum (vector<int> &num, int target)
	{
		vector<int> rs;
		Unordered_map<int, int> m;

		int i;
		for (i = 0; i < num.size (); i++)
			m[num[i]] = i;
		
		for (i = 0; i < num.size (); i++)
		{
			int sub = target-num[i];
			if (M.find (sub)!= m.end () && m[sub] > i)
			{
				Rs.push_back (i + 1);
				Rs.push_back (M[sub] + 1);
				break;
			}
		}

		return RS;
	}
;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.