LeetCode | Two sum

准备苦逼的开始看看算法,先从leetcode开始刷起~太菜太菜,不断学习不断敲代码,希望在这个过程中能有所提升。这个权当做个笔记,方便自己以后温故知新。代码也不工整,凑活着看。

另外有个大牛总结的题解,开源的共享在github上,我是自己先做做,再看看题解,争取能举一反三。贴个链接出来,好东西要大家共享着看。https://github.com/soulmachine/leetcode


进入正题

LeetCode–Two sum

题目:

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解决一:

首先,什么算法都不想,直接给它暴力解了!当然,运行时间就很长~跑了644ms
上代码:

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

解决二:

下来开始优化,用hash表来做。hash表存储每个数对应的数组下标。查找hash表的时间复杂度就很低了o(1)。这个只跑了36ms。
上代码:

#include
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       map<int,int> mapping;
       vector<int> vec;
       for(int i=0;i<nums.size();i++)
       {
           mapping[nums[i]]=i;
       }
       for(int j=0;j<nums.size();j++)
       {
           int gap=target-nums[j];
           if(mapping.find(gap)!=mapping.end() && mapping[gap]>j)
           {
              vec.push_back(j+1); 
              vec.push_back(mapping[gap]+1);
              return vec;
           }
       }
    }
};

解决三:

先排序,在查找。

等有空了再写。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值