您的位置:首页 > 其它

【LeetCode】Two Sum

2015-05-18 17:09 344 查看
题目描述

问题分析

代码

总结

个人声明

题目描述

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

问题分析

这道题初一看,应该会有三种解决方案:

直接暴力搜索,此时时间复杂度是o(n^2),显然这种方法并不可行

采用hash,存储每一个数值的对应下表,这个复杂度O(n)

对这个数组进行排序,然后进行查找,复杂度是O(nlogn),但是这个题要输出的是下表,并不合适

代码

struct Node
{
    int val;
    int index;
    Node(){}
    Node(int v, int idx):val(v), index(idx){}
};

bool compare(const Node &lhs, const Node &rhs)
{
    return lhs.val < rhs.val;
}

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<Node> a;
        for(int i = 0; i < numbers.size(); i++)
            a.push_back(Node(numbers[i], i + 1));
        sort(a.begin(), a.end(), compare);

        int i = 0;
        int j = numbers.size() - 1;
        while(i < j)
        {
            int sum = a[i].val + a[j].val;
            if (sum == target)
            {
                vector<int> ret;
                int minIndex = min(a[i].index, a[j].index);
                int maxIndex = max(a[i].index, a[j].index);
                ret.push_back(minIndex);
                ret.push_back(maxIndex);
                return ret;
            }
            else if (sum < target)
                i++;
            else
                j--;
        }
    }
};


总结

这个题并不是很难,找到思路还是很简单的

个人声明

本文章均为原创,转载请说明出处,谢谢

个人说明



本人对编程有很大兴趣,希望跟大家一起交流

欢迎访问个人论坛:www.dabenmo.com

如有任何问题请邮件:jianxiawzx@126.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: