算法课程Leetcode作业第一周技术博客

本文介绍了LeetCode经典题目TwoSum的两种解法,一种是使用双重循环的时间复杂度为O(n^2)的直接解法,另一种是利用哈希表进行优化,达到O(n)的时间复杂度。

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

算法课程Leetcode作业第一周技术博客

第一周的作业先尝试下easy难度试试水

题目:No.1 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] + nums1 = 2 + 7 = 9,
return [0, 1].**

分析:

题目描述其实很简单,从给定的vector里面找出两个相加等于target的数的下标,将下标存放在整型vector中作为返回值。
最简单的方法就是用两层嵌套的方式遍历所有组合方式,将两个数和target做比较,直到找到正确的位置后结束嵌套循环,这种算法的时间复杂度是 O(n2)

代码:

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

运行结果分析:

image_1bplkrnm914v81j917ufhll2tt9.png-145.8kB
这样的算法虽然简单但是运行时间也是较长的,因此我们尝试以下优化算法

算法优化

分析之前的算法,其最耗时的部分就是需要通过两个循环来找到相加为target的数,通常要优化时间复杂度需要牺牲空间,如果我们能只遍历一遍vector,然后找出第二个的数的位置,就能将 O(n2) 变成 O(n) ,也就是说找第二个数的时间复杂度为 O(1) ,满足这样条件的数据结构就是哈希表。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> hash_map;
        map<int, int>::iterator it;
        int second;
        vector<int> final;
        for (int i = 0; i < nums.size(); i++) {
            it = hash_map.find(target - nums[i]); //此时i不在map里面,不用担心重复??
            if (it == hash_map.end()) {
                hash_map.insert(pair<int, int>(nums[i], i));
            } else {
                final.push_back(it -> second);
                final.push_back(i);
                return final;
            }
        }
        return final;
    }
};

运行结果

image_1bpls9sbk1jsbcu43qh1i8c1bqt16.png-137.4kB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值