Two Sum

Two Sum

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

 

解题思路:

题目要求找出和为target的两个数的下标,那么如果直接对数组进行排序,然后采用两头夹的算法。显然是没法找到正确的答案,因为排序之后的数组的下标已经不是原来数组的下标。这时候考虑建立一个结构体,来保存数组的值和原始下标。然后对结构体生成的数组进行排序,求出两数之和为target的数。很自然的也可以得到对应的下标。该算法的时间复杂度主要在排序部分为O(nlogn);

 

Code:

struct Node{
	int val;
	int pos;
	Node(int v,int p)
	{
		val=v;
		pos=p;
	}
};

bool cmp(Node o1,Node o2)
{
	return o1.val<o2.val;
}
class Solution {
public:
    


vector<int> twoSum(vector<int> &numbers, int target)
{
    vector<int> ret;
	vector<Node> vtemp;
    for(int i=0;i<numbers.size();i++)
    {
		vtemp.push_back(Node(numbers[i],i+1));
    }

    sort(vtemp.begin(),vtemp.end(),cmp);
        
	for(int i=0,j=vtemp.size()-1;i!=j;)
    {
		int sum=vtemp[i].val+vtemp[j].val;
        if(sum==target)
        {
			if(vtemp[i].pos<vtemp[j].pos)
             {
                 ret.push_back(vtemp[i].pos);
                 ret.push_back(vtemp[j].pos);
             }
             else
             {
                 ret.push_back(vtemp[j].pos);
                 ret.push_back(vtemp[i].pos);
             }
             break;
	     }
         else if(sum<target)
             i++;
         else
             j--;
     }
     return ret;
}
};

 

另外在求该道题的时候,会相到用hash的方式去解决。

因此引入map,建立一个hash表,来存储每个数对应的下标。

 

参考代码:

vector<int> twoSum(vector<int>& num,int target){

    map<int,int> mapping;

    vector<int> ret;

    for(i=0;i<num.size();i++){

    const int gap=target-num[i];

    if(mapping.find(gap)!=mapping.end() && mapping[gap]>i){

        ret.push_back(i+1);

        ret.push_back(mapping[gap]+1);

        break;

    }

    }

   return ret;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值