LeetCode 1:两数之和

题目

在这里插入图片描述

解法1:暴力枚举

在写的时候必须要加入对应的头文件

< vector > 头文件指的是向量类型。

暴力枚举很简单,就是将其都遍历一遍然后寻找结果
这样时间复杂度是n^2,空间开销比较小,只有n
所以是以时间换空间。

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

    }
};

解法2:哈希表

一般空间够用,时间不够用
所以可以用二叉树搜索和哈希表
因为不需要维护数据的顺序性,所以使用哈希表。

建立哈希表,先把第一个元素放入
用target减去后面的每一个元素,如果最后的差在哈希表里面
就输出数组下表,不在哈希表内,就将其存入哈希表。

// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=1 lang=cpp
 *
 * [1] 两数之和
 */

// @lc code=start
#include <vector>
#include <iostream>
// 调用哈希表的标准库
#include <unordered_map>
using namespace std;
class Solution
{
public:
    vector<int> twoSum(vector<int> &nums, int target)
    {
        // 创建哈希表
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); i++)
        {
            //auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型
            // 在哈希表中寻找数值为target-nums[i]的
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end())
            // 如果没有到哈希表的尾部
            {
                return {it->second, i};
                // (*it).first;             // the key value (of type Key)
                // (*it).second;            // the mapped value (of type T)
                // (*it);                   // the "element value" (of type pair<const Key,T>) 

            }
            hashtable[nums[i]] = i;
            // 将数组下表存入值,将数组的值存入键
        }
        return {};
    }
};
// @lc code=end

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zeker62

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值