【LeetCode】.1.Two Sum

1. Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

Subscribe to see which companies asked this question

【分析】

      分析: 由于输入数组不一定是排序的,如果采用两重循环求解,时间复杂度为:O(n的平方),数据量位置的情况下,这种方式不可取。为了减小时间复杂度,我们可以先将输入数据进行排序,sort()函数的时间复杂度为:O(nlog2n);然后,我们再采用双指针两侧“夹逼”,便可以快速求解。考虑到需要输出的是原数组对应元素下标,排序后下标会改变,因此,我们在排序之前需要对每个元素的值及其下标进行记录,这一点通过结构体可以很容易解决。

【主要知识点】

     1.sort()函数的使用,注意对节点型数据(每一个节点包含多个数据)的排序需要一个bool型函数辅助,在本程序中,我们需要对节点中存放的原输入数据(value)进行排序,而不是位置下标(position),因此需要辅助函数cmp。在节点数据只有一个(一般的数组)的情况下,cmp可以缺省,默认升序排列。sort(Array.begin(),Array.end(),cmp),sort()函数前两个参数表示待排序数组的始末位置。

     2.双指针“夹逼”法的查找思想

【解法】

struct node
{
	int value;//存放数组元素
	int position;//存放数组元素对应下表
};
bool cmp(node a,node b)
{
	return a.value<b.value;//按value值,升序排列
}
class Solution6 {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> indices;
		vector<node> Array;//采用vector建立一个节点数组,用于存放输入数组数据及位置(下标)
		for(int i=0;i<nums.size();i++)
		{
			node temp;
			temp.value=nums[i];
			temp.position=i;
			Array.push_back(temp);
		}
		sort(Array.begin(),Array.end(),cmp);//将节点数组按数据(value)升序排列

        unsigned int High,Low;//定义两个指向节点数组两端(首尾)的下标变量
		High=Array.size()-1;//High节点数组尾端下标
		Low=0;//节点数组首端下标
		while(Low<High)//采用两端“夹逼”的方法
		{
			while(Low<High&&(Array.at(Low).value+Array.at(High).value>target))
				High--;
			while(Low<High&&Array.at(Low).value+Array.at(High).value<target)
				Low++;
			if(Array.at(Low).value+Array.at(High).value==target)
			{
				//找到对应的数据之后,比较其原始下标(position)的大小,从下到大存入indices容器
				if(Array.at(Low).position>Array.at(High).position)
				{
					indices.push_back(Array.at(High).position);
				    indices.push_back(Array.at(Low).position);
				}
				else
				{
				    indices.push_back(Array.at(Low).position);
				    indices.push_back(Array.at(High).position);
				}
				return indices;//查询到则返回(默认只有一组合适的数据能满足要求)
			}
		}
		return indices;	//未查询到,则返回空
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jin_Kwok

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值