LeetCode_1 TwoSum

看书虽然有必要,但是光看书大家斗志到是没用的,但是没办法,科研项目和互联网没关,只能找点题目来刷了!

不多说,开始!

LeetCode_1   TwoSum

题目说明:

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

翻译:给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。

要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。可以假设每一个输入肯定只有一个结果

拿到题先省清楚,一看到这题,肯定想到的是暴力法,但是不要接下去这样做,显然题目不会要求这么去做的,毕竟暴力法时间复杂度有点让人忍受不了,O(n^2)!

既然暴力法不行,很容易想到的方法有:

1、先排序,再两边往中间扫描;

2、哈希map(没去做)

本文主要是第一个方法,说下哈希表的思想(没实现):

先贴代码(通过验证):

<span style="font-size:18px;">#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void QuickSort(vector<int> & nums, int first, int last)
{
	// 快速排序 O(nlog2(n))
	int tmp;
	int i =first, j = last;
	vector<int>::iterator iter = nums.begin();
	if (first < last)
	{
		tmp = *(iter + first);
		while (i != j)
		{
			while (j > i && (*(iter + j) >= tmp))
				j--;
			*(iter + i) = *(iter + j);

			while (j > i && ( *(iter + i) <= tmp ) )
				i++;
			*(iter + j) = *(iter + i);
		}
		*(iter + i) = tmp;
		QuickSort(nums, first, i - 1);
		QuickSort(nums, i + 1, last);
	}
}

bool cmp(int a, int b)
{
	return a < b;
}

class Solution
{
public:
	vector<int> twoSum(vector<int>& nums, int target)
	{
		vector<int> Array;
		for(vector<int>::iterator iter = nums.begin();iter != nums.end(); iter++)
			Array.push_back(*iter);

		sort(nums.begin(), nums.end(), cmp);
		//QuickSort(nums, 0, nums.size() - 1); 

		vector<int> result;
		for (int i = 0, j = nums.size() - 1; i != j;)
		{
			int sum = *(nums.begin() + i) + *(nums.begin() + j);
			if ( sum == target )
			{
				int num1 = *(nums.begin() + i);
				int num2 = *(nums.begin() + j);
				vector<int> result;
				int tmp1 = 0, tmp2 = 0, k = 1;
				for(vector<int>::iterator iter = Array.begin(); iter != Array.end(); iter++, k++)
				{
					if(*iter == num1 || *iter == num2)
						result.push_back(k);
					if (result.size() == 2)
					    return result;
				}
			}
			else if(sum < target)
				i++;
			else if(sum > target)
				j--;
		}
	}
};</span>

首先,本来我自己写了个排序算法(快速排序),时间复杂度为O(nlog2n),但是在leetcode中上传后说超时,囧,后来用了自带的sort(algorithm头文件中),才没有出现超时的问题。

sort函数可以参考:http://blog.csdn.net/jiangyaoyan/article/details/5416983

我这里首先将数据背了个份,因为排序的时候肯定会破坏原来的顺序(也可以使用结构体,保存数据及其对应的位置,最后按照结构体的数据排序,这样即使原先的位置不一样了,结构体中也记录了原先元素对应的位置),排好序后,在两端设置指针,指针往中间靠拢即可。

如果所有的数据都是正的,还可以排好序后先从后往前扫,把大于target的元素直接排除,原因就不用我说了吧!

哈希表

至于哈希map是什么大家都不陌生,其拥有很好的搜索性能,所以要使用哈希map就要将问题转化到搜索上来。首先将元素及其下标作为<key,value>存入到hash-map中去,之后可取一个元素(假设为v1),则在hash-map中搜索(target - v1),由于哈希表的平均搜索次数为O(1),所以整个下来时间复杂度为O(n),比上面的方法好!实现可以参考:http://segmentfault.com/a/1190000002986095?_ea=258426

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-12-16 21:33:06

LeetCode_1 TwoSum的相关文章

JavaScript的two-sum问题解法

一个很常见的问题,找出一个数组中和为给定值的两个数的下标.为了简单一般会注明解只有一个之类的. 最容易想到的方法是循环遍历,这里就不说了. 在JS中比较优雅的方式是利用JS的对象作为hash的方式: 1 var twoSum = function(nums, target) { 2 var hash = {}; 3 var i; 4 for (var i = 0; i < nums.length; i++ ) { 5 if (typeof hash[nums[i]] !== "undefi

Leecode -- TwoSum

question: 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

[Lintcode two-sum]两数之和(python,双指针)

题目链接:http://www.lintcode.com/zh-cn/problem/two-sum/ 给一个整数数组,找到两个数使得他们的和等于一个给定的数target. 备份一份,然后排序.搞两个指针分别从左从右开始扫描,每次判断这两个数相加是不是符合题意,如果小了,那就把左边的指针向右移,同理右指针.然后在备份的数组里找到位置. 1 class Solution: 2 """ 3 @param numbers : An array of Integer 4 @param

LeetCode——TwoSum

题目: 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 t

leetcode中第一题twosum问题解答算法的可行性证明

leetcode中第一题twosum问题解答算法的可行性证明 一.引入 关于leetcode中第一题twosum问题,网上已有不少高人做出过解答,并提出了切实可行的算法实现.我在解答该题时参考了博客http://www.zixue7.com/article-9576-1.html的解答.为让读者更直观地阅读和理解本文,先简要摘录以上博客的内容如下: 题目还原 Two Sum Given an array of integers, find two numbers such that they a

leetcode001:TwoSum(5.5)

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

twoSum

1 package code; 2 3 /* Given an array of integers, find two numbers such that they add up to a specific target number. 4 5 The function twoSum should return indices of the two numbers such that they add up to the target, 6 where index1 must be less t

LeetCode 之 TwoSum

题目: 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 t

LeetCode 1 # TwoSum

LeetCode 1 # TwoSum 很有意思的问题. Two Sum Total Accepted: 63448 Total Submissions: 350576 My Submissions Question Solution Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return in