首页 > 代码库 > LeetCode:Two Sum

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)


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