[LeetCode]1. Two Sum

Description

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].

Discussion

看到这个问题的第一眼,最容易想到的方法自然是暴力破解。外层循环遍历每一个数,内层循环搜索符合条件的另一个数。暴力破解的复杂度为O(n^2)

外层循环难以优化,必然要遍历每一个数。内层的搜索如果可以转变为常数时间,那么整个算法的效率将会非常高。Java中我们可以采用Hash_Map来将搜索的时间复杂度变为O(1)。C++中我们可以采用unordered_map来将搜索的时间复杂度变为O(1)。这样,算法整体复杂度就降低到了O(n)

unordered_map属于C++11的新特性,是一个关联容器,包含带有唯一键的键值对。搜索,插入和去除具有常数时间复杂度。

算法的时间复杂度为O(n)。

C++ Code

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> answer;
        unordered_map<int, int> map;
        for (int i = 0; i < nums.size(); ++i)
        {
            map[nums[i]] = i;
        }
        for (int i = 0; i < nums.size(); ++i)
        {
            answer.push_back(i);
            int numToFind = target - nums[i];
                if (map.find(numToFind) != map.end() && map[numToFind] != i)
                {
                    answer.push_back(map[numToFind]);
                    return answer;
                }
            answer.clear();
        }
        return answer;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值