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...
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)....
Python匹配语句:match-case与switch对比
Python 3.10引入了match语句,这是一种强大的模式匹配机制,类似于其他语言中的switch语句,但功能更加强大。本文将详细介绍Python中match语句的用法。 一、match语句的基本用法1. 基本语法1234567891011121314def http_status(status): match status: case 200: return "OK" case 404: return "Not Found" case 500: return "Internal Server Error" case _: return "Unknown"print(http_status(200)) # 输出:OKprint(http_status(404)) # 输出:Not Foundprint(http_status(999)) ...
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...
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: [] 题目大意给定一棵二叉树的根节点...
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)...
C++ 虚函数访问控制
一、虚函数的访问控制虚函数的访问控制(public、protected、private)会影响其在派生类中的重写和调用规则,这是容易混淆的知识点。 1. public 虚函数基类中 public 的虚函数在派生类中可以被重写为 public 或 protected,但不能重写为 private(在 C++11 前允许,C++11 后被禁止): 123456789101112131415161718192021222324252627282930313233343536373839class Base {public: virtual void publicFunc() { cout << "Base::publicFunc" << endl; }};class Derived : public Base {public: // 正确:重写为public void publicFunc() override { cout <<...
Leetcode 0180. 连续出现的数字
180. 连续出现的数字表:Logs 12345678+-------------+---------+| Column Name | Type |+-------------+---------+| id | int || num | varchar |+-------------+---------+在 SQL 中,id 是该表的主键。id 是一个自增列。 找出所有至少连续出现三次的数字。 返回的结果表中的数据可以按 任意顺序 排列。 结果格式如下面的例子所示: 示例 1: 123456789101112131415161718192021输入:Logs 表:+----+-----+| id | num |+----+-----+| 1 | 1 || 2 | 1 || 3 | 1 || 4 | 2 || 5 | 1 || 6 | 2 || 7 | 2 |+----+-----+输出:Result 表:+-----------------+| ConsecutiveNums...
Leetcode 0162. Find Peak Element
162. Find Peak Element题目A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞. Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums =...
Leetcode 0155. Min Stack
155. Min StackDesign a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function. 题目大意设计一个支持...
Leetcode 0151. Reverse Words in a String
151. Reverse Words in a StringGiven an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. Example 1: 12Input: s...
Python异常处理:try-except-finally-else机制
Python的异常处理机制是一种强大的错误处理方式,使用try、except、finally和else关键字来捕获和处理程序运行过程中的错误。本文将详细介绍Python异常处理的各种用法。 一、基本语法1. try-except结构123456try: # 可能引发异常的代码 result = 10 / 0except ZeroDivisionError: # 处理特定异常 print("不能除以零") 2. 捕获异常信息12345try: result = 10 / 0except ZeroDivisionError as e: print(f"错误类型: {type(e).__name__}") print(f"错误信息: {e}") 3. 多个except子句1234567try: value = int("abc") result = 10 / 0except ValueError: ...
Leetcode 0150. Evaluate Reverse Polish Notation
150. Evaluate Reverse Polish NotationYou are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+', '-', '*', and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward zero. There will not be any division by zero. The input...
C++ 虚函数与多态实现机制
一、虚函数核心概念框架1.1 虚函数定义虚函数是通过virtual关键字声明的成员函数,允许派生类重写基类的行为。其本质是为实现运行时多态服务,通过动态绑定机制,在程序运行时决定调用哪个类的函数实现。 类比理解:想象一个图书馆管理系统,每个书架都有一个统一的借书接口。当借书时,系统根据实际书架类型( Hardcover/Book/Reference)选择对应的借书规则。 1.2 多态实现四要素 基类指针/引用 虚函数声明 派生类重写 动态绑定调用 关键概念:虚函数定义、多态特性、静态与动态绑定差异 示例: 12345678910111213141516171819202122232425262728293031323334353637#include <iostream>using namespace std;class Animal {public: virtual void speak() { cout << "Animal speak" <<...
Leetcode 0148. 排序链表
148. 排序链表给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 示例 1: 12输入:head = [4,2,1,3]输出:[1,2,3,4] 示例 2: 12输入:head = [-1,5,3,4,0]输出:[-1,0,3,4,5] 示例 3: 12输入:head = []输出:[] 题目大意给定链表的头节点 head,要求将链表按升序排列并返回排序后的链表头节点。 解题思路对于链表排序,最适合的高效算法是归并排序,原因如下: 归并排序的时间复杂度为 O (n log n),是链表排序的最优选择 链表的归并操作不需要像数组那样额外分配 O (n)...
Leetcode 0146. LRU Cache
146. LRU CacheDesign a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the...
Leetcode 0145. Binary Tree Postorder Traversal
145. Binary Tree Postorder TraversalGiven the root of a binary tree, return the postorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,6,7,5,2,9,8,3,1] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] 题目大意给定一棵二叉树的根节点 root,返回其节点值的后序遍历结果。后序遍历的顺序是「左子树 → 右子树 → 根节点」,遵循 "左 - 右 - 根"...
Leetcode 0144. Binary Tree Preorder Traversal
144. Binary Tree Preorder TraversalGiven the root of a binary tree, return the preorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [1,2,4,5,6,7,3,8,9] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] 题目大意给定一棵二叉树的根节点 root,返回其节点值的前序遍历结果。前序遍历的顺序是「根节点 → 左子树 → 右子树」,遵循 "根 - 左 - 右"...

