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

Leetcode 01 Two Sum

时间:2015-06-23 23:04:42      阅读:126      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!