算法-两数之和

两数之和

题目:

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

提示:

2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
 

解题:

第一次尝试,暴力循环遍历,时间O(N*N)

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

执行用时:8 ms, 在所有 C++ 提交中击败了62.55%的用户

内存消耗:8.7 MB, 在所有 C++ 提交中击败了71.91%的用户

暴力流,时间上肯定不讨好

第二次尝试,map上场,时间比暴力流还长,不明觉厉

O(logN)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        std::map<int, int> maps;
        for (int i = 0; i < nums.size(); ++i) {
            int diff = target - nums[i];
            try {
                // 从map中直接找
                if (maps.at(diff) != i) {
                    // 找到了,且不是自身,则有效
                    std::vector<int> ret;
                    ret.push_back(i);
                    ret.push_back(maps[diff]);
                    return ret;
                }
            } catch (exception e) {
                // 不是,则放入maps
            	maps[nums[i]] = i;
            }
        }
        return vector<int>();
    }
};

执行用时:12 ms, 在所有 C++ 提交中击败了32.49%的用户

内存消耗:10.7 MB, 在所有 C++ 提交中击败了5.01%的用户

第三次尝试,hash上场

std::map是红黑树实现的,居然用时比循环还多,这让人感觉到不科学,构建查找都花时间,尝试再优化下,用unordered_map,其是hash实现的, hash的单次查找是O(1),这样就快多了

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        std::unordered_map<int, int> maps; // hash实现
        for (int i = 0; i < nums.size(); ++i) {
            int diff = target - nums[i];
            try {
                if (maps.at(diff) != i) {
                    std::vector<int> ret;
                    ret.push_back(i);
                    ret.push_back(maps[diff]);
                    return ret;
                }
            } catch (exception e) {
                maps[nums[i]] = i;
            }
        }
        return vector<int>();
    }
};

执行用时:4 ms, 在所有 C++ 提交中击败了93.77%的用户

内存消耗:9.3 MB, 在所有 C++ 提交中击败了14.42%的用户

 

这道题,如果nums是排好序的话,会有另外一种解法,那就是双指针法。

作者:帅得不敢出门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值