LeetCode Algorithms #1 Two Sum

来源:互联网 发布:昆明行知中学招聘 编辑:程序博客网 时间:2024/06/05 16:48

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%。

原创粉丝点击