LeetCode_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 

参见《编程之美》2.12快速寻找满足条件的两个数。这里采用的解法2中的hash表,采用C++中的map容器,以数组元素为key,因为要返回下标,以下标为value。算法时间复杂度O(n),空间复杂度O(n).

代码(AC):

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    map<int,int> map1;//<数值,下标> 
    vector<int> vin;
    
    int len = numbers.size();
    //cout<<len<<endl;
    for(int i = 0;i<len;i++)
    {
            map1[numbers[i]] = i;
    }
    for(int i = 0;i<len;i++)
    {
            int sum = target - numbers[i];
            map<int,int>::iterator it = map1.end();
            if(it != map1.find(sum)&&map1.find(sum)->second!=i)
            {
                  
                  vin.push_back(i+1);
                  vin.push_back(map1.find(sum)->second+1);
                 
            }
    } 
    return vin;
    }
};
如果不要求返回符合条件元素在原数组的下标,《编程之美》中的解法三很巧妙。如果已经了这个数组任意两个元素之和的有序数组,那么采取Binary Search,在O(logN)时间内就可以解决问题。但是计算每两个元素和的有序数组需要O(n^2),我们并不需要求解这个数组。这个思考启发我们,可以直接对两个数字的和进行有序遍历,降低时间复杂度。

首选,对原数组进行排序,采用Qsort,时间复杂度O(NlogN);

声明两个下标,i = 0;j = n-1;比较array[i]+array[j]是否等于target,如果是返回array[i]和array[j],若小于target,则i++;如果大于target,则

j--;遍历一次即可。时间复杂度O(n).所以该方法的时间复杂度是O(n)+O(NlogN) = O(NlogN)。要是题目返回原始数组的下标,则在对原数组排序的时候要保存各个元素在原数组的下标。

伪代码:

Qsort(array);

for (i=0,j=n-1;i<j)

if(array[i]+array[j]==target) return (array[i],array[j]);

else if(array[i]+array[j]<target) i++;

else j--;

return ;




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值