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

 

这一题最简单的思路就是利用冒泡排序的思想,每两个数碰一下,然后看看是不是等于target,所以很明显,时间复杂度是n^{2},这个思路我就不写了很简单,leetcode排序比较靠前的写法都是利用了map这种数据结构,思路如下:

首先找到当前遍历的数的余数(相对于target)

然后和之前的数进行查找,是否能找到这个余数,

找到即返回结果,找不到则将当前的数和index压入map中,

这样在查找中采用的是hash查找,相对于遍历要快,时间复杂度是log(n)所以一共是nlog(n)的时间复杂度。

以下是我的方案:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector <int> result;
        int num = nums.size();
        map <int,int> front_elem;
        for(int i = 0; i <num; i++)
        {
            int target_left = target - nums[i];
            if(front_elem.find(target_left) != front_elem.end())  //核心知识点,当采用map的find的时候,如果find不到目标元素,返回的是.end(),但这个不是map最后一个迭代器,而是最后一个元素的下一个的迭代器,可以理解为是结束迭代器
            {
                result.push_back(front_elem[target_left]);
                result.push_back(i);
                return result;
            }
            else
            {
                front_elem.insert(pair<int,int>(nums[i],i));
            }
        }
        return result;
    }
};

参考:https://stackoverflow.com/questions/9961742/time-complexity-of-find-in-stdmap

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值