【C++学习】LeetCode No.1 两数之和
·
写在前面
想在现有的技术栈上,提高 C++ 的技能点。
这是新时代的学习方法:AI托举,边做边学。
目录
4. STL(Standard Template Library)是什么?
5. LRU缓存机制(Least Recently Used cache)
做题

做题思路
一般通过遍历完成的,都可以通过map来提高运行效率(空间换时间)。
题解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
/* 基础遍历+比较
for (int i = 0; i < nums.size(); i++) {
if (nums[i] <= valid_max) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[j] <= valid_max) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
}
}
return {};
*/
// map
map<int, int> nums_posi;
for (int i = 0; i < nums.size(); i++) {
int sub = target - nums[i];
if (nums_posi.find(sub) != nums_posi.end()) {
return {nums_posi[sub], i};
}
nums_posi[nums[i]] = i;
}
return {};
}
};
知识点
1. vector 的使用
动态数组,类似于 python 的列表,golang 的 slice。
// 导入
#include < vector>
using namespace std;
// 定义
vector<int> nums = {2, 7, 11, 15};
// 插入
nums.push_back(20); // 动态添加元素
c++ “列表” 的对比(Based deepseek):


2. 函数定义
返回值 函数名(参数...) {}
3. 引用和指针的关系和区别
总结:引用优先,指针备用。


// 引用声明与使用
int& ref = value; // 必须初始化
ref = 100; // 直接使用,像普通变量
std::cout << value; // 输出 100
// 指针声明与使用
int* ptr = &value; // 获取地址
*ptr = 200; // 解引用修改
std::cout << value; // 输出 200
// 引用 - 必须初始化
int x = 5;
int& ref1 = x; // ✅ 正确
// int& ref2; // ❌ 错误!必须初始化
// 指针 - 可以不初始化(但危险!)
int* ptr1 = nullptr; // ✅ 良好实践
int* ptr2; // ✅ 语法正确,但危险!
// *ptr2 = 10; // ❌ 未定义行为!
int a = 1, b = 2, c = 3;
// 引用 - 终身绑定
int& ref = a; // ref 永远绑定到 a
ref = b; // 这是赋值,a 现在等于 2
ref = c; // a 现在等于 3
// 指针 - 灵活重指向
int* ptr = &a; // 指向 a
ptr = &b; // 现在指向 b
ptr = &c; // 现在指向 c
#include <algorithm>
// vector 排序
sort(nums.begin(), nums.end());
// 取最大值,最小值
// min_element, max_element 返回的是迭代器的引用,因此需要 * 引用
int min_val = *min_element(nums.begin(), nums.end());
int max_val = *max_element(nums.begin(), nums.end());
4. STL(Standard Template Library)是什么?
STL(标准模板库)算法库是C++标准库(Standard Template Library)的一部分。
STL 分为多个组件,包括容器(Containers)、迭代器(Iterators)、算法(Algorithms)、函数对象(Function Objects)和适配器(Adapters)等。(vector 就是 STL 的一部分)
使用 STL 的好处:
- 代码复用:STL 提供了大量的通用数据结构和算法,可以减少重复编写代码的工作。
- 性能优化:STL 中的算法和数据结构都经过了优化,以提供最佳的性能。
- 泛型编程:使用模板,STL 支持泛型编程,使得算法和数据结构可以适用于任何数据类型。
- 易于维护:STL 的设计使得代码更加模块化,易于阅读和维护。
5. LRU缓存机制(Least Recently Used cache)
面试可能会考究 c++ 实现
即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。LRU算法的设计原则是:如果一个数据在最近一段时间没有被访问到,那么在将来它被访问的可能性也很小。也就是说,当限定的空间已存满数据时,应当把最久没有被访问到的数据淘汰。
更多推荐


所有评论(0)