{LeetCode} 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 thesame element twice.

Example:

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

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


一道非常简单的问题,过AC很容易,先上代码。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for(int i = 0; i<nums.size(); i++)
        {
            for(int j = i+1; j<nums.size(); j++)
            {
                if(nums.at(i)+nums.at(j) == target)
                {
                    vector<int> output;
                    output.push_back(i);
                    output.push_back(j);
                    return output;
                }
            }
        }
    }
};

Runtime在200ms开外,并不是非常的理想。因为代码运行在O(n^2)的时间复杂度上。


在看了几个大神的操作之后,使用unordered_map,改进到O(n)上看看如何。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector <int> output;
        unordered_map <int, int> hash_table;
        for(int i = 0; i<nums.size(); i++)
        {
            int numNeed  = target - nums.at(i);
            if(hash_table.find(numNeed)!=hash_table.end())
            {
                output.push_back(hash_table[numNeed]);
                output.push_back(i);
                return output;
            }
            else
            {
                hash_table[nums.at(i)] = i;
            }
        }
        
    }
};
平均跑完test case的Runtime降到9ms。

另一个思路一样的实现,修改自于Angel1a的代码,runtime进一步降到6ms。原因应该是unordered_map还是有些冗余。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int MAX = 99999;
        int DELT = 49999;
        vector<int> ans;
        int x[MAX];
        memset(x, 0, sizeof(x));
        for (int i = 0; i < nums.size(); i++)
        {
            if (x[nums[i] + DELT])
            {
                ans.push_back((x[nums[i] + DELT] - 1));
                ans.push_back(i);
                return ans;
            }
            x[target - nums[i] + DELT] = i + 1;
        }
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值