first init

This commit is contained in:
flowerstonezl
2026-01-29 17:04:05 +08:00
commit e1006fa09c
51 changed files with 4288 additions and 0 deletions

View File

@@ -0,0 +1,143 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# [35. 搜索插入位置](https://leetcode.cn/problems/search-insert-position)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 题目描述\n",
"\n",
" 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。\n",
"\n",
"请必须使用时间复杂度为 `O(log n)` 的算法。\n",
"\n",
"**示例 1:**\n",
"\n",
"```txt\n",
"输入: nums = [1,3,5,6], target = 5\n",
"输出: 2\n",
"```\n",
"\n",
"**示例 2:**\n",
"\n",
"```txt\n",
"输入: nums = [1,3,5,6], target = 2\n",
"输出: 1\n",
"```\n",
"\n",
"**示例 3:**\n",
"\n",
"```txt\n",
"输入: nums = [1,3,5,6], target = 7\n",
"输出: 4\n",
"```\n",
"\n",
"**提示:**\n",
"\n",
"- `1 <= nums.length <= 10^4`\n",
"- `-10^4 <= nums[i] <= 10^4`\n",
"- `nums` 为 **无重复元素** 的 **升序** 排列数组\n",
"- `-10^4 <= target <= 10^4`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 解答\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Solution(object):\n",
" def searchInsert(self, nums, target):\n",
" \"\"\"\n",
" :type nums: List[int]\n",
" :type target: int\n",
" :rtype: int\n",
" \"\"\"\n",
" left, right = 0, len(nums) - 1\n",
" while left < right:\n",
" mid = (left + right) // 2\n",
" if target > nums[mid]:\n",
" left = mid + 1\n",
" elif target < nums[mid]:\n",
" right = mid\n",
" else:\n",
" return mid \n",
" return left if nums[left] >= target else left + 1 # 注意这里的返回值 注意溢出"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "a1e23e83",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
}
],
"source": [
"test_nums = [1,3,5,6]\n",
"test_target = 7\n",
"solution_1 = Solution()\n",
"result_1 = solution_1.searchInsert(test_nums, test_target)\n",
"print(result_1) # 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "92764a56",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
}
},
"nbformat": 5,
"nbformat_minor": 10
}

View File

@@ -0,0 +1,91 @@
"""
LeetCode 解题模板
使用方法:
1. 在 Solution 类中实现你的算法
2. 在 if __name__ == "__main__" 中添加测试用例
3. 运行python solution.py
"""
from typing import List
class Solution:
"""
示例:搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
"""
def searchInsert(self, nums: List[int], target: int) -> int:
"""
搜索插入位置
Args:
nums: 排序数组
target: 目标值
Returns:
目标值的索引,如果不存在则返回插入位置
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
def print_test_result(test_name: str, passed: bool):
"""打印测试结果"""
status = "✓ 通过" if passed else "✗ 失败"
print(f"{test_name}: {status}")
def assert_equals(actual: int, expected: int) -> bool:
"""比较两个整数是否相等"""
return actual == expected
if __name__ == "__main__":
solution = Solution()
# 测试用例 1: 目标值存在于数组中
nums1 = [1, 3, 5, 6]
target1 = 5
result1 = solution.searchInsert(nums1, target1)
expected1 = 2
print_test_result("测试用例 1: 目标值存在", assert_equals(result1, expected1))
# 测试用例 2: 目标值不存在,应插入到中间位置
nums2 = [1, 3, 5, 6]
target2 = 2
result2 = solution.searchInsert(nums2, target2)
expected2 = 1
print_test_result("测试用例 2: 插入中间位置", assert_equals(result2, expected2))
# 测试用例 3: 目标值大于所有元素
nums3 = [1, 3, 5, 6]
target3 = 7
result3 = solution.searchInsert(nums3, target3)
expected3 = 4
print_test_result("测试用例 3: 插入末尾", assert_equals(result3, expected3))
# 测试用例 4: 目标值小于所有元素
nums4 = [1, 3, 5, 6]
target4 = 0
result4 = solution.searchInsert(nums4, target4)
expected4 = 0
print_test_result("测试用例 4: 插入开头", assert_equals(result4, expected4))
print("\n所有测试完成!")