【LeetCode刷题日记01】Two Sum

这篇博客介绍了LeetCode上的Two Sum问题,首先阐述了题目的要求,即找到数组中两个数的索引,使得它们相加等于目标值。然后,作者详细讲解了暴力解法的时间复杂度,并提出使用unordered_map进行优化,通过键值对查找降低时间复杂度,提高解题效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题目

        Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

        You may assume that each input would have exactly one solution, and you may not use the same element twice.

        You can return the answer in any order.

即在一列向量中找到两个数的索引,使两个数相加等于给定的target数值。

Example :

        Input: nums = [2,7,11,15], target = 9
        Output: [0,1]
        Output: Because nums[0] + nums[1] == 9, we return [0, 1].

二、暴力解法-第一次解题

        for循环嵌套,时间复杂度为o(n^{2}

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

 三、代码优化

        利用unordered_map进行键值对的查找,for循环中每次进行检验看target和num[i]的差值是否在unordered_map对象中,如果不在,就把当前num[i]添加进unordered_map中,以便后面进行检索;如果在就进行返回。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //创建一个unordered_map,内部实现哈希表,无序性导致查找速度很快
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i) {
            //count函数由于元素不重复只能为0和1
            if (m.count(target - nums[i])) {
                return {i, m[target - nums[i]]};
            }
            //以值为索引
            m[nums[i]] = i;
        }
        return {};
    }
};

参考:https://www.cnblogs.com/grandyang/p/4130379.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值