码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Two Sum

时间:2014-05-21 07:42:18      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目:


      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)


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


LeetCode:Two Sum,布布扣,bubuko.com

LeetCode:Two Sum

标签:leetcode

原文地址:http://blog.csdn.net/dream_you_to_life/article/details/26366357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!