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


are turned 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


解题思路:


    由于返回值需要找寻满足等式的索引位置,所以我在结构体中用了一个变量pos记录该数字在原数组


中的位置,然后对结构体进行排序,最后线性遍历一遍即可知满足条件的索引位置.时间复杂度为(nlgn).


解题代码:

class Solution {
public: 
    struct Node
    {
        int val,pos;
        bool operator < (const Node &tmp) const
        {
            return val < tmp.val ;
        }
    };
    vector<int> twoSum(vector<int> &numbers, int target) 
    {
        vector<Node> vec(numbers.size());
        for(unsigned i=0;i<numbers.size();++i)
            vec[i].val = numbers[i] , vec[i].pos = i ;
        sort(vec.begin(),vec.end());
        unsigned i=0 , j = numbers.size() - 1 ;
        while( i < j)
        {
            long long tmp = vec[i].val + vec[j].val ;
            if(tmp == target)
                break;
            tmp > target ? --j : ++i ;
        }
        i = vec[i].pos , j = vec[j].pos ;
        if(i > j)
            swap(i,j);
        vector<int> res;
        res.push_back(i+1);
        res.push_back(j+1);
        return res;
    }
};

    注:关于上述代码中的结构体是自己迫不得已才这样做的,由于对类中的定义及调用什么的不熟悉,


所以才想到这么一个办法,如果您在阅读时发现您能额加的O(n)空间解决(不是类似我用结构体的O(2n)


的空间),请您在留下您的思路,谢谢!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值