LeetCode Algorithms #1 Two Sum

LeetCode Algorithms #1 Two Sum

题目内容

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解题

最简单的解法

最简单的,不用说,自然是双层循环枚举所有组合,时间复杂度为O(n2),写作

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

        int length = nums.size(), i, j;
        bool flag = true;  //为的是得到结果之后快速跳出循环
        for(i = 0; i < length && flag; i++) {
            for(j = i+1; j < length && flag; j++) {
                if(nums[i]+nums[j] == target)
                    flag = false;
            }
        }

        vector<int> result;
        result.push_back(i-1);
        result.push_back(j-1);
        return result;
    }
};

但是这样自然是很慢的,我的运行时间是133ms,只超过了30.73%的人。

更快的方法

不知道为什么,看到这道题的时候第一个想法就是排序之后夹逼,但是由于题目中给的是vector<int>,如果排序的话要在排序的过程中将其索引值也交换,才能正确的indice,其中的假想是否成立也没有经过仔细考虑。不过为了刷时间,还是想了一下这个想法。

首先有一点是由于题目明确给出答案存在并且唯一的,不会因为std::sort()的不稳定性返回错误的答案(比如要求返回第一对满足的结果,std::sort()将几个相同值的索引打乱后没法确定第一个)。

a0...an1为排序之后的数组,数组长度为nxy为对应的结果,则方法就是使用一个head标记指向a0,rear标记指向an1,当head标记值和rear标记值相加大于目标时将rear向前移动一个位置,若小于则将head向后移动一个位置,若等于则跳出循环。

a0,a1...ax...ay...an2,an1

没有经过详细的证明,只是简单的想了一下情况。假设这个方法不正确的,那不正确的过程应该发生在某一个标记值跨过xy的时候。假设0i<xy<jn1。若i跨越,当i增加到x的时候,ai+aj=ax+aj>ax+ay,无法继续增加发生跨越。同理当j减少的时候,也无法跨越过y

#include <algorithm>
#include <utility>
struct node {
    int value;
    int index;
    node(int a, int b):value(a), index(b){}
};

bool compare(const node* a, const node* b) {
        return a->value < b->value;
}

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int rear = nums.size()-1, head = 0;

        vector<node*> n;
        for(int i = 0; i <= rear; ++i)
            n.push_back(new node(nums[i], i));
        sort(n.begin(), n.end(), compare);

        int sum;
        while(rear > head) {
            sum = n[head]->value + n[rear]->value;
            if(sum == target)
                break;
            else if(sum > target)
                --rear;
            else
                ++head;
        }

        int a = n[head]->index, b = n[rear]->index;
        if(a > b)
            swap(a, b);
        vector<int> result;
        result.push_back(a);
        result.push_back(b);
        return result;
    }
};

最后是运行时间6ms,超过82.12%。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值