码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_1题

时间:2015-04-17 13:41:24      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

Two Sum

 Total Accepted: 81397 Total Submissions: 459615My Submissions

 

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

 

Hide Tags
 Array Hash Table
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

开始想直接按正常的最简单方法两个循环来做,结果发现提交时,超出了内存,显然这道题不能这样做

接下来,又想是不是顺序的,就把后面的数给砍掉,结果发现是无需的数列

在接下来,又想把比目标数字大的全部砍掉,结果发现有负数,这种方法也不行。

lass Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        	vector<int> last_result;
	vector<int> temp;
	int len=numbers.size();
	int realy_size;
	for(int i=0;i!=len;i++)
	{
		if(numbers[i]<target)
		{
			realy_size=i;
			temp.push_back(numbers[i]);
		}
	}
	realy_size=temp.size();
	for(int i=0;i!=realy_size-1;++i)
	{
		for(int j=i+1;j!=realy_size;++j)
		{
			if(numbers[i]+numbers[j]==target)
			{
				last_result.push_back(i+1);
				last_result.push_back(j+1);
				return last_result;
			}
		}
	}
	return last_result;
    }
};

  看来非得需要用hash表来做

leetcode_1题

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4434339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!