首页 > 其他 > 详细

Leetcode 01 Two Sum

时间:2015-06-23 23:02:36      阅读:259      评论:0      收藏:0      [点我收藏+]

Leetcode 01 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

第一种解法 排序

class Solution
{
private:
    class node
    {
    public:
        int no;
        int val;
    };
    class cmp_class
    {
    public:
        bool operator ()(const node& a, const node& b)
        {
            return a.val < b.val;
        }
    }cmp;
public:
        vector<int> twoSum(vector<int>& nums, int target)
        {
            vector<node> line;
            vector<int> result(2,0);
            for (vector<int>::const_iterator it=nums.begin();it!=nums.end();it++)
            {
                node *temp=new node;
                (*temp).no=it-nums.begin()+1;(*temp).val=(*it);
                line.push_back(*temp);
                delete temp;
            }
            sort(line.begin(),line.end(),cmp);
            vector<node>::const_iterator l=line.begin();
            vector<node>::const_iterator r=line.end()-1;
            while (l<r)
            {
                int *p=new int;
                *p=(*l).val+(*r).val;
                if ((*p)==target)
                {
                    result[0]=min((*l).no,(*r).no);
                    result[1]=max((*l).no,(*r).no);
                    break;
                }
                else
                if ((*p)<target)
                {
                    l++;
                }
                else
                {
                    r--;
                }
                delete p;
            }
            return result;
        }
};

第二种解法 map

class Solution2
{
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
        map<int, int> hmap;
        vector<int> result;
        for (vector<int>::const_iterator iter = nums.begin(); iter != nums.end(); iter++)
        {
            map<int, int>::const_iterator fit = hmap.find(target-*iter);
            if (fit == hmap.end())
            {
                hmap.insert(pair<int, int>( *iter,iter-nums.begin()+1));
            }
            else
            {
                result.push_back(fit->second);
                result.push_back(iter - nums.begin() + 1);
                break;
            }
        }
        return result;
    }
};

 

Leetcode 01 Two Sum

原文:http://www.cnblogs.com/chenwanqq-leetcode/p/4596345.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!