LeetCode 刷题 1. 两数之和

文章介绍了LeetCode上的一道经典问题——两数之和,提供了两种解题思路:1.暴力枚举,通过双重循环遍历数组,时间复杂度为O(N^2);2.使用哈希表,先遍历数组构建哈希表,然后查询目标值减去当前数的差,时间复杂度优化到O(N)。
摘要由CSDN通过智能技术生成

LeetCode 刷题 1. 两数之和

题目

给定一个整数数组nums和目标值target,请再数值中找出和为目标值得两个整数,并返回下标值。你可以假设每个输入只对应一种答案,但不能利用这个数组中重复得元素。

解题思路

1. 暴力枚举

思路及算法:
枚举数组中的每一个整数x,在剩余的数组中寻找target-x;需要注意的是,数组中的每一个变量只枚举一次,因此在遍历时,只需要遍历x之后的整数即可;

#include <iostream>
#include <vector>

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 {};
    }

};

int main()
{
    vector<int> nums{ 2, 7, 11, 15 };
    int target = 14;
    Solution m_solution;
    vector<int> index = m_solution.twoSum(nums, target);
}
  • 时间复杂度:O(N2)
  • 空间复杂度:O(1)

2. 哈希表

思路及算法:
首先创建一个哈希表,对于数组中的每一个x,可以现在哈希表中查询是否催在target-x,若存在,则直接返回数组与索引,若不存在,则将当前数组存储为键值key,其对应索引存储为值value。

#include <iostream>
#include <vector>
#include <unordered_map>

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 {};
    }

    vector<int> twoSum2(vector<int>& nums, int target) {
        unordered_map<int, int> hashtable;    //创建一个无序哈希表
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            auto it = hashtable.find(target - nums[i]);  //查找是否存在target-nums[i]
            if (it != hashtable.end()) {
                return { it->second, i };    //存在则范围搜索到的键值对应的value,与当前数组的索引
            }
            hashtable[nums[i]] = i;   //若未搜索到,则存入当前整数数组及其索引

        }

        return {};
    }

};

int main()
{
    vector<int> nums{ 2, 7, 11, 15 };
    int target = 9;
    Solution m_solution;
    vector<int> index = m_solution.twoSum2(nums, target);
}
  • 时间复杂度:O(N)
  • 空间复杂度:O(N)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值