CONST AUTO 的应用
一、const auto迭代器的适用场景1. 只读访问容器元素时当你只需要读取容器元素而不需要修改它们时,应该使用const auto声明迭代器: 1234567891011121314151617#include <vector>#include <iostream>void printData(const std::vector<int>& data) { // 函数参数为const引用,只能使用const迭代器 for (const auto it = data.begin(); it != data.end(); ++it) { std::cout << *it << " "; // 只读访问 // *it = 100; // 编译错误,不允许修改 } std::cout << std::endl;}int main() { std::vector<int&...
Leetcode 0349. Intersection of Two Arrays
349. Intersection of Two ArraysGiven two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. Example 1: 12Input: nums1 = [1,2,2,1], nums2 = [2,2]Output: [2] Example 2: 123Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output: [9,4]Explanation: [4,9] is also accepted. 题目大意给定两个整数数组 nums1 和 nums2,返回它们的交集。结果中的每个元素必须是唯一的,并且可以按任意顺序返回。 解题思路可以使用哈希集合来高效求解: 先将第一个数组中的元素存入一个哈希集合,自动去除重复元素 遍历第二个数组,检查每个元...
Leetcode 0316. 去除重复字母
316. 去除重复字母给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。 示例 1: 12输入:s = "bcabc"输出:"abc" 示例 2: 12输入:s = "cbacdcbc"输出:"acdb" 核心思路是单调栈 + 贪心算法,通过维护一个单调递增的栈来确保字典序最小,同时利用计数数组判断字符是否还有剩余,确保每个字符只保留一次: 预处理: 统计字符串中每个字符的出现次数(count 数组); 记录字符是否已在栈中(in_stack 数组),避免重复添加。 单调栈逻辑: 遍历字符串中的每个字符C: 减少 count[c](当前字符已被考虑); 若 c 已在栈中,直接跳过; 若 c 不在栈中,且栈不为空,且栈顶字符大于 c,且栈顶字符在后续还有出现(count[栈顶字符] > 0),则弹出栈顶字符(确保字典序更小); 将 c 压入栈,并标记为已在栈中。 结果构建: 栈中字符即为去重...
C++ 静态成员与单例模式:从基础到线程安全实现
一、静态成员的本质与特性1.1 静态数据成员:类级别的共享状态静态数据成员不属于任何对象实例,而是属于整个类,其内存空间在程序生命周期内唯一存在。 123456789101112131415161718192021222324252627#include <iostream>class Counter {private: // 静态数据成员声明:类内声明,类外定义 static int s_totalInstances; int m_id; // 非静态成员:每个对象拥有独立副本public: Counter() { m_id = ++s_totalInstances; // 每次创建对象自增计数 } int getId() const { return m_id; } static int getTotalInstances() { return s_totalInstances; }};// 静态数据成员必须在类外定义(C++17...
Leetcode 0287. Find the Duplicate Number
287. Find the Duplicate NumberGiven an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and using only constant extra space. Example 1: 12Input: nums = [1,3,4,2,2]Output: 2 Example 2: 12Input: nums = [3,1,3,4,2]Output: 3 Example 3: 12Input: nums = [3,3,3,3,3]Output: 3 题目大意给定一个包含 n + 1 个整数的数组 nums,其中每个整数都在 [1...
Leetcode 0283. Move Zeroes
283. Move Zeroes题目Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example 1: 12Input: [0,1,0,3,12]Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. 解法1:双指针1234567891011121314151617181920class Solution {public: void moveZeroes(vector<int>& nums) { int n = nums.size(); int i = 0; // 慢指针,记录下...
继承与多态
一、继承机制:代码复用的基石1.1 继承的概念与本质继承是面向对象编程中实现代码复用的核心机制,它允许一个类(派生类)获取另一个类(基类)的成员变量和成员函数。这种关系类似于现实世界中的 "is-a" 关系,例如 "狗是一种动物"。 在 C++ 中,继承通过类定义时的冒号语法实现: 12345678910111213class Animal {public: void speak() { std::cout << "The animal makes a sound." << std::endl; }};class Dog : public Animal {public: void bark() { std::cout << "The dog barks." << std::endl; }}; 在上述示例中,Dog 类继承自...
Leetcode 0257. Binary Tree Paths
257. Binary Tree PathsGiven the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: 12Input: root = [1,2,3,null,5]Output: ["1->2->5","1->3"] Example 2: 12Input: root = [1]Output: ["1"] 题目大意给定一棵二叉树的根节点 root,返回所有从根节点到叶子节点的路径。叶子节点是指没有子节点的节点,路径以字符串形式表示,节点值之间用 "->" 连接。 例如: 输入二叉树 [1,2,3,null,5],根到叶子的路径为 1->2->5 和 1->3,返回 ["1->2->5","1->3"]。 解题思...
Leetcode 0239. Sliding Window Maximum
239. Sliding Window MaximumYou are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Example 1: 1234567891011Input: nums = [1,3,-1,-3,5,3,6,7], k = 3Output: [3,3,5,5,6,7]Explanation: Window position Max--------------- -----[1 3 -1] -3 5 3 6 ...
C++中class与struct的异同点深度解析
一、基础语法差异1.1 访问修饰符差异 class 默认成员访问权限为 private 声明的成员变量与函数仅对类内部可见,需使用 public/protected 显式开放 struct 默认成员访问权限为 public 结构体成员对所有作用域开放,需使用 private/protected 显式限制 12345678910class MyClass { int privateVar; // 默认私有public: void publicFunc() {}};struct MyStruct { int publicVar; // 默认公有 void publicFunc() {}}; 1.2 成员函数特性 class 支持抽象方法(纯虚函数) 通过 = 0 定义的虚函数使类成为抽象类,如 virtual void func() = 0; struct 不支持抽象方法 所有成员函数必须有具体实现,否则会导致编译错误 12...
Leetcode 0232. Implement Queue using Stacks
232. Implement Queue using StacksImplement a first in first out (FIFO) queue using only two Stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty, false otherwise. No...
C++ 析构函数详解:原理、实现
一、析构函数基础概念1.1 析构函数的定义析构函数是 C++ 面向对象编程中用于对象销毁时进行资源清理的特殊成员函数。当对象生命周期结束时,析构函数会被自动调用,负责释放对象所占用的资源。 语法特征: 函数名与类名相同,前面加波浪号~ 没有返回值,也不指定 void 没有参数,因此无法重载 不能被显式调用(编译器自动调用) 123456789101112class MyClass {public: // 构造函数 MyClass() { std::cout << "构造函数被调用" << std::endl; } // 析构函数 ~MyClass() { std::cout << "析构函数被调用" << std::endl; }}; 1.2 析构函数的调用时机析构函数在以下情况会被自动调用: 栈上创建的对象超出其作用域时 堆上创建的对象...
Leetcode 0227. Basic Calculator II
227. Basic Calculator IIGiven a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). 题目大意给定一个字符串 s 表示一个算术表达式,要求计算该表达式的值并返回。表达式仅包含非负整数、+、-、*、/ 四种运算符,以及可能的空格。整数除法需要向...
C++ 左值与右值:语义解析与实战应用
一、左值与右值的核心定义在 C++ 中,表达式根据其特性被分为左值(lvalue)和右值(rvalue),这一分类直接影响着变量的存储、引用绑定和资源管理。根据 C++17 标准( IO/IEC 14882:2017),左值是指 "可以取地址且具有身份 (identity) 的表达式",而右值则是 "非左值的表达式",通常是临时的、不具有持久身份的对象。 1.1 左值的核心特征左值具有以下关键特性: 可以通过&运算符获取地址S 具有持久性,在表达式结束后仍然存在 可以出现在赋值运算符的左侧 1234int x = 10; // x是左值int* ptr = &x; // 合法,左值可以取地址x = 20; // 合法,左值可以出现在赋值左侧 1.2 右值的核心特征右值具有以下关键特性: 不能通过&运算符获取地址 临时性,通常在表达式结束后销毁 不能出现在赋值运算符的左侧 1234int y = x + 5; // x + 5是右值// int* ptr = &(x + ...
Leetcode 0226. Invert Binary Tree
226. Invert Binary TreeGiven the root of a binary tree, invert the tree, and return its root. Example 1: 12Input: root = [4,2,7,1,3,6,9]Output: [4,7,2,9,6,3,1] Example 2: 12Input: root = [2,1,3]Output: [2,3,1] Example 3: 12Input: root = []Output: [] 题目大意给定一棵二叉树的根节点 root,翻转这棵二叉树(即交换每个节点的左子树和右子树),并返回翻转后的根节点。 例如: 输入二叉树 [4,2,7,1,3,6,9],翻转后每个节点的左右子树互换,输出为 [4,7,2,9,6,3,1]。 解题思路翻转二叉树的核心是交换每个节点的左子节点和右子节点,可以通过递归或迭代两种方式实现: 1. 递归法利用二叉树的递归性质: 若当前节点为空,直接返回; 否则,先交换当前节点的左、右子节点; 递归翻转当前节点的左子树和右子树。 2...
Leetcode 0225. Implement Stack using Queues
225. Implement Stack using QueuesImplement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: void push(int x): Pushes element x to the top of the stack. int pop(): Removes the element on the top of the stack and returns it. int top(): Returns the element on the top of the stack. boolean empty(): Returns true if the stack is empty, false otherwise. Notes: ...
C++ 变量作用域与存储持续度完全解析
导言:变量类型的四维属性体系在 C++ 中,每个变量都具有四个核心属性,这些属性共同决定了变量的行为特征: 作用域 (Scope):变量在程序中可见的区域 存储持续度 (Storage Duration):变量在内存中存在的时间 链接属性 (Linkage):变量在不同编译单元间的可见性 生命周期 (Lifetime):变量从创建到销毁的时间段 一、作用域类型详解1.1 块作用域 (Block Scope)块作用域是由花括号{}界定的区域,包括函数体、循环体、条件语句体等。 12345678910void function() { int a = 0; // 块作用域开始 if (a == 0) { int b = 1; // 内部块作用域 // a和b在此可见 } // b的作用域结束 // 仅a可见,b不可见} // a的作用域结束 1.2 函数作用域 (Function Scope)仅适用于goto语句的标签,标签在整个函数内可见。 12345678vo...
Leetcode 0222. Count Complete Tree Nodes
222. Count Complete Tree NodesGiven the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity. Example 1: 12Input: root = [1,2,3,4,5,6]Output: 6 Example 2: 12Input: root ...
Leetcode 0216. Combination Sum III
216. Combination Sum IIIFind all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. Example 1: 12345Input: k = 3, n = 7Output: [[1,2,4]]Explanation:1 + 2 + 4 = 7There are no other valid combinations. Example 2: 1234567Input: k ...
Leetcode 0209. Minimum Size Subarray Sum
209. Minimum Size Subarray Sum题目Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example 1: 123Input: s = 7, nums = [2,3,1,2,4,3]Output: 2Explanation: the subarray [4,3] has the minimal length under the problem constraint. Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 解题思路这一题的解题思...
Leetcode 0206. Reverse Linked List
206. Reverse Linked ListGiven the head of a singly linked list, reverse the list, and return the reversed list. Example 1: 12Input: head = [1,2,3,4,5]Output: [5,4,3,2,1] Example 2: 12Input: head = [1,2]Output: [2,1] Example 3: 12Input: head = []Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000 解法 1:迭代解法123456789101112131415161718192021222324252627/** * Definition for singly-linked list. * struct ListNode { * int v...
Leetcode 0199. Binary Tree Right Side View
199. Binary Tree Right Side ViewGiven the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Explanation: Example 2: Input: root = [1,2,3,4,null,null,null,5] Output: [1,3,4,5] Explanation: Example 3: Input: root = [1,null,3] Output: [1,3] Example 4: Input: root = [] Output: [] 题目大意给定一棵二叉树的根节点 root,想象自己站在树的右侧,返回从顶部到底...
Leetcode 0189. 轮转数组
189. 轮转数组给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 示例 1: 123456输入: nums = [1,2,3,4,5,6,7], k = 3输出: [5,6,7,1,2,3,4]解释:向右轮转 1 步: [7,1,2,3,4,5,6]向右轮转 2 步: [6,7,1,2,3,4,5]向右轮转 3 步: [5,6,7,1,2,3,4] 示例 2: 12345输入:nums = [-1,-100,3,99], k = 2输出:[3,99,-1,-100]解释: 向右轮转 1 步: [99,-1,-100,3]向右轮转 2 步: [3,99,-1,-100] 题目大意给定一个整数数组 nums 和非负整数 k,将数组元素向右轮转 k 个位置(即每个元素向右移动 k 位,末尾元素移动到开头)。要求尽可能优化时间和空间复杂度。 核心解题思路:三次反转法常规思路(如临时数组、多次右移)要么空间复杂度高(O (n)),要么时间复杂度高(O (nk))。三次反转法通过巧妙的反转操作,实现 O (n) 时间复杂度 + O (1) 空间复杂度...

