Leetcode 0977. Squares of a Sorted Array
977. Squares of a Sorted ArrayGiven an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: 12Input: [-4,-1,0,3,10]Output: [0,1,9,16,100] Example 2: 12Input: [-7,-3,2,3,11]Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order. 解题思路这一题由于原数组是有序的,所以要尽量利用这一特点来减少时间复杂度。 最终返回的数组,最后一位,是最大值,这个值应该是由原数组最大值,或者最小值得来的,所以可...
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: pri...
C++ 虚函数与多态实现机制
一、虚函数核心概念框架1.1 虚函数定义虚函数是通过virtual关键字声明的成员函数,允许派生类重写基类的行为。其本质是为实现运行时多态服务,通过动态绑定机制,在程序运行时决定调用哪个类的函数实现。 类比理解:想象一个图书馆管理系统,每个书架都有一个统一的借书接口。当借书时,系统根据实际书架类型( Hardcover/Book/Reference)选择对应的借书规则。 1.2 多态实现四要素 基类指针/引用 虚函数声明 派生类重写 动态绑定调用 关键概念:虚函数定义、多态特性、静态与动态绑定差异 示例: 12345678910111213141516171819202122232425262728293031323334353637#include <iostream>using namespace std;class Animal {public: virtual void speak() { cout << "Animal speak" << en...
Leetcode 0016.3Sum Closest(python)
16. 3Sum Closest题目Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: 123Input: nums = [-1,2,1,-4], target = 1Output: 2Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: 12Input: nums = [0,0,0], target = 1Output: 0 题目大意在整数数组中找出三个数,使其和最接近给定的目标值 target。题目保证有且仅有一个解。 你选用...
Leetcode 0922. Sort Array By Parity II
922. Sort Array By Parity IIGiven an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: 123Input: nums = [4,2,5,7]Output: [4,5,2,7]Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: 12Input: nums = [2,3]Output: [2,3] 双指针解法: 初始化: 偶数索引指针 i 从 0 开始,每次移动 2 步...
Leetcode 0015.3Sum(python)
15. 3Sum题目Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: 12345678Input: nums = [-1,0,1,2,-1,-4]Output: [[-1,-1,2],[-1,0,1]]Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.Different triplets are [-1,0,1...
Python条件表达式:链式比较与短路求值
Python支持一种独特的语法特性:条件表达式可以连写。这种链式比较(Chained Comparisons)可以让代码更加简洁和易读。本文将详细介绍Python中条件表达式连写的用法。 一、链式比较的基本用法1. 数学风格比较123456789# 传统写法x = 5if x > 0 and x < 10: print("x在0到10之间")# Python连写写法x = 5if 0 < x < 10: print("x在0到10之间") 2. 更多示例1234567891011121314# 判断是否在某个范围内age = 25if 18 <= age <= 65: print("工作年龄") # 输出:工作年龄# 链式不等式x = 0.5if 0 < x < 1: print("x是0到1之间的分数") # 输出:x是0到1之间的分数# 多个比较a, b, c = 3, 5, 7if a < b < c: ...
Leetcode 0905. Sort Array By Parity
905. Sort Array By ParityGiven an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. Example 1: 123Input: nums = [3,1,2,4]Output: [2,4,3,1]Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Example 2: 12Input: nums = [0]Output: [0] 解法1:双指针12345678910111213141516class Solution{public: vector<int> sortArrayByParity(vector<int> &...
C++多态机制解析:重载、重写与隐藏
一、概念C++ 的多态机制主要通过三个核心概念实现,它们在编译和运行时有着截然不同的处理方式: 概念 定义 绑定时机 核心特征 函数重载 同一作用域内,函数名相同但参数列表不同的函数 编译时 静态多态,基于参数列表区分 函数重写 派生类中重新定义基类中的虚函数,函数签名完全相同 运行时 动态多态,基于对象实际类型调用 函数隐藏 派生类中定义的函数遮蔽基类中同名函数,无论参数是否相同 编译时 名称遮蔽,基类函数被隐藏 注:函数签名包括函数名、参数类型和顺序,不包括返回值类型 二、函数重载解析函数重载是 C++ 实现静态多态的基础机制,允许在同一作用域内定义多个同名函数,通过参数列表的差异进行区分。 重载的实现原理编译器在编译阶段会对重载函数进行名称修饰(Name Mangling),根据函数名和参数列表生成唯一的内部名称,因此重载函数在底层实际上拥有不同的标识符。 重载示例代码123456789101112131415161718192021222324252627282930313233343536373839#include <iostream...
派生类对象复制控制
一、复制控制的核心概念与场景复制控制机制是C++中处理对象创建、复制和销毁的核心手段。在继承体系中,当派生类对象被复制时,需要特别关注以下关键点: 复制场景 拷贝构造函数调用:当用已存在的对象初始化新对象时 赋值操作符调用:当用一个对象赋值给另一个对象时 析构函数调用:当对象生命周期结束时 典型问题 浅拷贝导致的指针悬挂(dangling pointer) 资源泄漏(resource leak) 自赋值(self-assignment)引发的异常 二、派生类复制的构造函数调用链12345678910111213class Base {public: Base() { /* 基类构造 */ } Base(const Base& other) { /* 基类拷贝构造 */ } ~Base() { /* 基类析构 */ }};class Derived : public Base {public: Derived() : Base() { ...
Leetcode 0014. Longest Common Prefix (python)
14. Longest Common Prefix 你选用何种方法解题? 方法 核心思路 时间复杂度 空间复杂度 说明 方法一:横向扫描 依次比较相邻两个字符串的公共前缀 O(S) O(1) 最直观:逐个比较 方法二:纵向扫描 按字符位置逐列比较所有字符串 O(S) O(1) 提前终止:遇到不匹配立即返回 方法三:二分查找 在最短字符串长度范围内二分查找 O(S×log(minLen)) O(1) 适合长字符串 方法二是推荐解:纵向扫描可以提前终止,实际性能更好。 解题过程核心洞察最长公共前缀的长度不可能超过最短字符串的长度。 纵向扫描步骤12345输入: ["flower","flow","flight"]第1列: f, f, f → 全部相同,继续第2列: l, l, l → 全部相同,继续第3列: o, o, i → 不相同,返回前2个字符 "fl" 边界情况 场景 输入 结果 空数组 [] "" 单元素 ["a"]...
Leetcode 0904. Fruit Into Baskets
904. Fruit Into Baskets题目In a row of trees, the i-th tree produces fruit with type tree[i]. You start at any tree of your choice, then repeatedly perform the following steps: Add one piece of fruit from this tree to your baskets. If you cannot, stop. Move to the next tree to the right of the current tree. If there is no tree to the right, stop. Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then st...
Python条件语句:if-elif-else分支结构
Python的条件语句用于根据不同的条件执行不同的代码块。本文将详细介绍Python中if、elif、else条件语句的使用方法。 一、基本语法1. 简单的if语句1234x = 10if x > 5: print("x大于5") # 输出:x大于5 2. if-else语句123456x = 3if x > 5: print("x大于5")else: print("x不大于5") # 输出:x不大于5 3. if-elif-else语句12345678910score = 85if score >= 90: print("优秀")elif score >= 80: print("良好") # 输出:良好elif score >= 70: print("中等")else: print("及格") 二、Python与C++的对比1. 条件表达式C++: 1234...
Leetcode 0013. Roman to Integer (python)
13. Roman to Integer题目Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 12345678Symbol ValueI 1V 5X 10L 50C 100D 500M 1000 For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from le...
C++ 继承机制中的类型转换
一、对象赋值的双向可行性分析1.1 基类到派生类的转换 隐式转换: 不允许直接赋值(如 Base b = d;) 显式转换: 需使用构造函数或类型转换运算符 123456789101112class Base {public: Base() {} explicit Base(int val) : data(val) {}private: int data;};class Derived : public Base {public: Derived(int val) : Base(val) {}}; 内存影响: 派生类对象包含基类数据成员,赋值操作不会改变大小,但会丢失派生类特有数据 1.2 派生类到基类的转换 隐式转换: 允许(如 Base b = d;) 显式转换: 可使用static_cast或构造函数 123Derived d;Base b = d; // 隐式转换Base& br = static_cast<...
Leetcode 0844. Backspace String Compare
844. Backspace String Compare题目Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: 123Input: S = "ab#c", T = "ad#c"Output: trueExplanation: Both S and T become "ac". Example 2: 123Input: S = "ab##", T = "c#d#"Output: trueExplanation: Both S and T become "". Example 3: 123Input: S = "a##c", T = "#a#c"Output: trueExplanation: Bo...
Leetcode 0826. Most Profit Assigning Work
826. Most Profit Assigning WorkYou have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then th...
Python全局变量:作用域与global关键字
在Python编程中,全局变量和局部变量的作用域是一个重要的概念。本文将详细介绍Python中全局变量的使用,以及如何通过global关键字在函数内部修改全局变量。 一、全局变量和局部变量1. 基本概念123456789101112# 全局变量global_var = 10def func(): # 局部变量 local_var = 20 print(f"Inside function: global_var = {global_var}") print(f"Inside function: local_var = {local_var}")func()print(f"Outside function: global_var = {global_var}")# print(local_var) # NameError: name 'local_var' is not defined 2. 作用域规则12345678...
Leetcode 0012. Integer to Roman (python)
12. Integer to Roman题目Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 12345678Symbol ValueI 1V 5X 10L 50C 100D 500M 1000 For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from le...
Leetcode 0825. Friends Of Appropriate Ages
825. Friends Of Appropriate AgesThere are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 * age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise, x will send a friend request to y. Note that if x sends a request to y, y will not necessarily send a request to x. Also, a ...
C++ virtual 继承机制详解(非多态场景)
一、virtual 继承的核心作用在C++中,virtual关键字用于解决多重继承时的菱形继承问题。当多个派生类共享同一基类时,如果不使用虚继承,会导致基类对象被多次实例化,造成内存浪费和指针混淆。 1.1 问题场景考虑经典菱形继承结构: 12345678910111213141516class A {public: int a;};class B : virtual public A {public: int b;};class C : virtual public A {public: int c;};class D : public B, public C {}; 在这种情况下,D对象会包含两个A子对象(一个来自B,一个来自C),导致: 内存重复占用(每个A子对象占用相同内存空间) 指针访问歧义(需要明确使用B::a或C::a) 1.2 解决方案通过在继承声明中添加virtual关键字,可以确保基类A仅被实例化一次: 12345678910111213141516clas...
Leetcode 0011. Container With Most Water (python)
11. Container With Most Water题目You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i-th line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. Example 1: 1234Input: height = [1,8,6,2,5,4,8,3,7]Output: 49Explanation: The above vertical...
Leetcode 0707. Design Linked List
707. Design Linked ListDesign your implementation of the linked list. You can choose to use a singly or doubly linked list.A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. Implement the MyLinkedList ...
Python函数副作用:返回值与状态变更
在Python编程中,理解函数副作用(Side Effects)是非常重要的。副作用是指函数在执行过程中,除了返回值之外,对外部状态产生的任何改变。理解副作用有助于编写更清晰、更安全的代码。 一、什么是函数副作用1. 基本定义副作用包括但不限于: 修改全局变量 修改传入的参数 输入/输出操作(打印、读取文件、网络通信等) 修改数据结构 抛出异常 2. 无副作用函数示例1234567# 无副作用:纯函数def add(a, b): return a + bresult = add(3, 5)print(result) # 输出:8# 函数外部没有任何改变 3. 有副作用函数示例12345678910# 有副作用:修改全局变量counter = 0def increment(): global counter counter += 1 return counterprint(increment()) # 输出:1print(counter) # 输出:1(全局变量被修改) 二、常见的副作用场景1. 修改全局变量123456789...
Leetcode 0704. Binary Search
704. Binary Search题目Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Note: You may assume that all elements in nums are un...

