first init
This commit is contained in:
41
array/1binary search/27remove_target/CMakeLists.txt
Normal file
41
array/1binary search/27remove_target/CMakeLists.txt
Normal file
@@ -0,0 +1,41 @@
|
||||
# 1. 指定CMake最低版本要求
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
# 2. 设置项目信息
|
||||
project(
|
||||
27remove_target # 项目名称
|
||||
VERSION 1.0.0 # 项目版本
|
||||
DESCRIPTION "Simple C++ Project"
|
||||
LANGUAGES CXX # 支持的语言
|
||||
)
|
||||
|
||||
# 设置C++标准
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_C_COMPILER "g++")
|
||||
# 源文件收集
|
||||
file(GLOB_RECURSE SOURCES "src/*.cpp") # 递归收集源文件
|
||||
file(GLOB_RECURSE HEADERS "include/*.h") # 头文件
|
||||
|
||||
# 8. 创建目标
|
||||
# 可执行文件目标
|
||||
add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})
|
||||
|
||||
# 14. 自定义目标
|
||||
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
|
||||
# 设置输出目录
|
||||
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
|
||||
|
||||
# 配置调试信息(默认启用)
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
add_compile_options(-g3 -O0)
|
||||
endif()
|
||||
|
||||
# 13.2 生成版本信息
|
||||
configure_file(
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/cmake/Version.hpp.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/Version.hpp
|
||||
)
|
||||
|
||||
|
||||
|
||||
49
array/1binary search/27remove_target/kotlin/App.kt
Normal file
49
array/1binary search/27remove_target/kotlin/App.kt
Normal file
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* This Kotlin source file was generated by the Gradle 'init' task.
|
||||
*/
|
||||
package binarySearch
|
||||
|
||||
class Solution {
|
||||
fun removeElement(nums: IntArray, target: Int): Int {
|
||||
var fast_index :Int = 0
|
||||
var slow_index :Int = 0
|
||||
while (fast_index < nums.size) {
|
||||
if (nums[fast_index] != target) {
|
||||
nums[slow_index] = nums[fast_index]
|
||||
slow_index++
|
||||
}
|
||||
fast_index++
|
||||
}
|
||||
return slow_index
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// 测试用例
|
||||
fun main() {
|
||||
val nums = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8)
|
||||
|
||||
println("请输入要剔除的数字:")
|
||||
val input = readLine()
|
||||
|
||||
// 验证输入有效性
|
||||
if (input.isNullOrBlank()) {
|
||||
println("错误:未输入任何内容")
|
||||
return
|
||||
}
|
||||
|
||||
val target = input.toIntOrNull() ?: run {
|
||||
println("错误:请输入有效的整数")
|
||||
return
|
||||
}
|
||||
|
||||
val solution = Solution()
|
||||
val result = solution.removeElement(nums, target )
|
||||
if (result == -1){
|
||||
println("不存在$target")
|
||||
}
|
||||
else{
|
||||
println("删除后数组长度: $result")
|
||||
}
|
||||
}
|
||||
|
||||
153
array/1binary search/27remove_target/python/27. 移除元素.ipynb
Normal file
153
array/1binary search/27remove_target/python/27. 移除元素.ipynb
Normal file
@@ -0,0 +1,153 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# [27. 移除元素](https://leetcode.cn/problems/remove-element)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 题目描述 \n",
|
||||
"\n",
|
||||
"给你一个数组 `nums` 和一个值 `val`,你需要 **[原地](https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95)** 移除所有数值等于 `val` 的元素。元素的顺序可能发生改变。然后返回 `nums` 中与 `val` 不同的元素的数量。\n",
|
||||
"\n",
|
||||
"假设 `nums` 中不等于 `val` 的元素数量为 `k`,要通过此题,您需要执行以下操作:\n",
|
||||
"\n",
|
||||
"- 更改 `nums` 数组,使 `nums` 的前 `k` 个元素包含不等于 `val` 的元素。`nums` 的其余元素和 `nums` 的大小并不重要。\n",
|
||||
"- 返回 `k`。\n",
|
||||
"\n",
|
||||
"**用户评测:**\n",
|
||||
"\n",
|
||||
"评测机将使用以下代码测试您的解决方案:\n",
|
||||
"\n",
|
||||
"```txt\n",
|
||||
"int[] nums = [...]; // 输入数组\n",
|
||||
"int val = ...; // 要移除的值\n",
|
||||
"int[] expectedNums = [...]; // 长度正确的预期答案。\n",
|
||||
" // 它以不等于 val 的值排序。\n",
|
||||
"\n",
|
||||
"int k = removeElement(nums, val); // 调用你的实现\n",
|
||||
"\n",
|
||||
"assert k == expectedNums.length;\n",
|
||||
"sort(nums, 0, k); // 排序 nums 的前 k 个元素\n",
|
||||
"for (int i = 0; i < actualLength; i++) {\n",
|
||||
" assert nums[i] == expectedNums[i];\n",
|
||||
"}\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"如果所有的断言都通过,你的解决方案将会 **通过**。\n",
|
||||
"\n",
|
||||
"**示例 1:**\n",
|
||||
"\n",
|
||||
"```txt\n",
|
||||
"输入:nums = [3,2,2,3], val = 3\n",
|
||||
"输出:2, nums = [2,2,_,_]\n",
|
||||
"解释:你的函数函数应该返回 k = 2, 并且 nums 中的前两个元素均为 2。\n",
|
||||
"你在返回的 k 个元素之外留下了什么并不重要(因此它们并不计入评测)。\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"**示例 2:**\n",
|
||||
"\n",
|
||||
"```txt\n",
|
||||
"输入:nums = [0,1,2,2,3,0,4,2], val = 2\n",
|
||||
"输出:5, nums = [0,1,4,0,3,_,_,_]\n",
|
||||
"解释:你的函数应该返回 k = 5,并且 nums 中的前五个元素为 0,0,1,3,4。\n",
|
||||
"注意这五个元素可以任意顺序返回。\n",
|
||||
"你在返回的 k 个元素之外留下了什么并不重要(因此它们并不计入评测)。\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"**提示:**\n",
|
||||
"\n",
|
||||
"- `0 <= nums.length <= 100`\n",
|
||||
"- `0 <= nums[i] <= 50`\n",
|
||||
"- `0 <= val <= 100`"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"---\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 解答"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class Solution(object):\n",
|
||||
" def removeElement(self, nums, val):\n",
|
||||
" \"\"\"\n",
|
||||
" :type nums: List[int]\n",
|
||||
" :type val: int\n",
|
||||
" :rtype: int\n",
|
||||
" \"\"\"\n",
|
||||
" slow_index = 0\n",
|
||||
" for fast_index in range(len(nums)):\n",
|
||||
" if nums[fast_index] != val:\n",
|
||||
" nums[slow_index] = nums[fast_index]\n",
|
||||
" slow_index += 1\n",
|
||||
" return slow_index, nums[:slow_index]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "ac31a7c1",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"原始数组: 3223\n",
|
||||
"原始数组长度: 4\n",
|
||||
"剔除3后数组: (2, [2, 2])\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"solution = Solution()\n",
|
||||
"nums = [3,2,2,3]\n",
|
||||
"val = 3\n",
|
||||
"print('原始数组:',''.join(map(str, nums)))\n",
|
||||
"print('原始数组长度:', len(nums))\n",
|
||||
"print('剔除3后数组:', solution.removeElement(nums, val)) # Output: 2"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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
|
||||
}
|
||||
39
array/1binary search/27remove_target/src/27.cpp
Normal file
39
array/1binary search/27remove_target/src/27.cpp
Normal file
@@ -0,0 +1,39 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int removeElement(vector<int>& nums, int val) {
|
||||
|
||||
int count = nums.size();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (nums[i] != val)
|
||||
{
|
||||
nums[slow_index] = nums[i];
|
||||
slow_index++;
|
||||
}
|
||||
}
|
||||
return slow_index;
|
||||
|
||||
}
|
||||
private:
|
||||
|
||||
int slow_index = 0;
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> nums = {0, 1, 2, 2, 3, 0, 4, 2};
|
||||
int val = 2;
|
||||
Solution solution;
|
||||
int result = solution.removeElement(nums, val);
|
||||
cout << "The length of nums after removing val is: " << result << endl;
|
||||
for (int i = 0; i < result; i++)
|
||||
{
|
||||
cout << nums[i] << " ";
|
||||
}
|
||||
system("pause");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# 1. 指定CMake最低版本要求
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
|
||||
# 2. 设置项目信息
|
||||
project(
|
||||
LeetCodeSolution # 项目名称(可根据题目修改)
|
||||
VERSION 1.0.0 # 项目版本
|
||||
DESCRIPTION "LeetCode Solution Template"
|
||||
LANGUAGES CXX # 支持的语言
|
||||
)
|
||||
|
||||
# 3. 设置C++标准和编译特性
|
||||
set(CMAKE_CXX_STANDARD 17) # 使用C++17标准
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON) # 必须支持指定标准
|
||||
set(CMAKE_CXX_EXTENSIONS OFF) # 禁用编译器特有扩展
|
||||
|
||||
# 4. 配置构建类型和编译选项
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Debug) # 默认构建类型为Debug(便于调试)
|
||||
endif()
|
||||
|
||||
# 公共编译选项
|
||||
add_compile_options(
|
||||
"$<$<CONFIG:Release>:-O2>" # Release模式优化
|
||||
"$<$<CONFIG:Debug>:-g>" # Debug模式包含调试信息
|
||||
"$<$<CONFIG:Debug>:-O0>" # Debug模式不优化
|
||||
)
|
||||
|
||||
# 平台特定选项
|
||||
if(MSVC)
|
||||
add_compile_options(/W3) # MSVC: 警告等级3(刷题时不需要太严格)
|
||||
else()
|
||||
add_compile_options(-Wall -Wextra) # GCC/Clang: 常用警告
|
||||
endif()
|
||||
|
||||
# 5. 源文件收集
|
||||
file(GLOB_RECURSE SOURCES "src/*.cpp") # 递归收集源文件
|
||||
|
||||
# 6. 创建可执行文件目标
|
||||
add_executable(${PROJECT_NAME} ${SOURCES})
|
||||
|
||||
# 7. 自定义目标:运行程序
|
||||
add_custom_target(run
|
||||
COMMAND ${PROJECT_NAME}
|
||||
DEPENDS ${PROJECT_NAME}
|
||||
COMMENT "运行 ${PROJECT_NAME}..."
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
113
array/1binary search/35search-insert-position/c++/src/main.cpp
Normal file
113
array/1binary search/35search-insert-position/c++/src/main.cpp
Normal file
@@ -0,0 +1,113 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <cassert>
|
||||
|
||||
using namespace std;
|
||||
|
||||
/**
|
||||
* LeetCode 解题模板
|
||||
*
|
||||
* 使用方法:
|
||||
* 1. 在 Solution 类中实现你的算法
|
||||
* 2. 在 main 函数中添加测试用例
|
||||
* 3. 编译运行:mkdir build && cd build && cmake .. && make && ./Solution
|
||||
*/
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* 示例函数:搜索插入位置
|
||||
*
|
||||
* @param nums 排序数组
|
||||
* @param target 目标值
|
||||
* @return 目标值的索引,如果不存在则返回插入位置
|
||||
*/
|
||||
int searchInsert(vector<int> &nums, int target)
|
||||
{
|
||||
left = 0;
|
||||
right = nums.size() - 1;
|
||||
while (left < right)
|
||||
{
|
||||
int mid = (left + right) >> 1;
|
||||
if (nums[mid] == target)
|
||||
{
|
||||
return mid;
|
||||
}
|
||||
else if (nums[mid] < target)
|
||||
{
|
||||
left = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
right = mid;
|
||||
}
|
||||
}
|
||||
return target<=nums[left]?left:left+1;
|
||||
}
|
||||
|
||||
private:
|
||||
int left;
|
||||
int right;
|
||||
};
|
||||
|
||||
// 辅助函数:打印测试结果
|
||||
void printTestResult(const string &testName, bool passed)
|
||||
{
|
||||
cout << testName << ": " << (passed ? "pass" : "fail") << endl;
|
||||
}
|
||||
|
||||
// 辅助函数:比较两个整数
|
||||
bool assertEquals(int actual, int expected)
|
||||
{
|
||||
return actual == expected;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
Solution solution;
|
||||
|
||||
// 测试用例 1: 目标值存在于数组中
|
||||
{
|
||||
vector<int> nums = {1, 3, 5, 6};
|
||||
int target = 5;
|
||||
int result = solution.searchInsert(nums, target);
|
||||
int expected = 2;
|
||||
cout<< "result: "<<result<<", expected: "<<expected<<endl;
|
||||
printTestResult("test 1: target exists", assertEquals(result, expected));
|
||||
}
|
||||
|
||||
// 测试用例 2: 目标值不存在,应插入到中间位置
|
||||
{
|
||||
vector<int> nums = {1, 3, 5, 6};
|
||||
int target = 2;
|
||||
int result = solution.searchInsert(nums, target);
|
||||
int expected = 1;
|
||||
cout<< "result: "<<result<<", expected: "<<expected<<endl;
|
||||
printTestResult("test 2: insert middle", assertEquals(result, expected));
|
||||
}
|
||||
|
||||
// 测试用例 3: 目标值大于所有元素
|
||||
{
|
||||
vector<int> nums = {1, 3, 5, 6};
|
||||
int target = 7;
|
||||
int result = solution.searchInsert(nums, target);
|
||||
int expected = 4;
|
||||
cout<< "result: "<<result<<", expected: "<<expected<<endl;
|
||||
printTestResult("test 3: insert end", assertEquals(result, expected));
|
||||
}
|
||||
|
||||
// 测试用例 4: 目标值小于所有元素
|
||||
{
|
||||
vector<int> nums = {1, 3, 5, 6};
|
||||
int target = 0;
|
||||
int result = solution.searchInsert(nums, target);
|
||||
int expected = 0;
|
||||
cout<< "result: "<<result<<", expected: "<<expected<<endl;
|
||||
printTestResult("test 4: insert beginning", assertEquals(result, expected));
|
||||
}
|
||||
|
||||
cout << "\nAll test cases pass." << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* LeetCode 解题模板
|
||||
*
|
||||
* 使用方法:
|
||||
* 1. 在 Solution 类中实现你的算法
|
||||
* 2. 在 main 函数中添加测试用例
|
||||
* 3. 运行:kotlinc Solution.kt -include-runtime -d Solution.jar && java -jar Solution.jar
|
||||
* 或者使用 IDE(如 IntelliJ IDEA)直接运行
|
||||
*/
|
||||
|
||||
/**
|
||||
* 示例:搜索插入位置
|
||||
*
|
||||
* 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
|
||||
* 如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
|
||||
*
|
||||
* 请必须使用时间复杂度为 O(log n) 的算法。
|
||||
*/
|
||||
class Solution {
|
||||
/**
|
||||
* 搜索插入位置
|
||||
*
|
||||
* @param nums 排序数组
|
||||
* @param target 目标值
|
||||
* @return 目标值的索引,如果不存在则返回插入位置
|
||||
*/
|
||||
fun searchInsert(nums: IntArray, target: Int): Int {
|
||||
var left = 0
|
||||
var right = nums.size - 1
|
||||
|
||||
while (left <= right) {
|
||||
val mid = left + (right - left) / 2
|
||||
when {
|
||||
nums[mid] == target -> return mid
|
||||
nums[mid] < target -> left = mid + 1
|
||||
else -> right = mid - 1
|
||||
}
|
||||
}
|
||||
|
||||
return left
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印测试结果
|
||||
*/
|
||||
fun printTestResult(testName: String, passed: Boolean) {
|
||||
val status = if (passed) "pass" else "fail"
|
||||
println("$testName: $status")
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个整数是否相等
|
||||
*/
|
||||
fun assertEquals(actual: Int, expected: Int): Boolean {
|
||||
return actual == expected
|
||||
}
|
||||
|
||||
fun main() {
|
||||
val solution = Solution()
|
||||
|
||||
// 测试用例 1: 目标值存在于数组中
|
||||
val nums1 = intArrayOf(1, 3, 5, 6)
|
||||
val target1 = 5
|
||||
val result1 = solution.searchInsert(nums1, target1)
|
||||
val expected1 = 2
|
||||
printTestResult("test case 1:target exists $target1", assertEquals(result1, expected1))
|
||||
|
||||
// 测试用例 2: 目标值不存在,应插入到中间位置
|
||||
val nums2 = intArrayOf(1, 3, 5, 6)
|
||||
val target2 = 2
|
||||
val result2 = solution.searchInsert(nums2, target2)
|
||||
val expected2 = 1
|
||||
printTestResult("test case 2:insert in middle $target2", assertEquals(result2, expected2))
|
||||
|
||||
// 测试用例 3: 目标值大于所有元素
|
||||
val nums3 = intArrayOf(1, 3, 5, 6)
|
||||
val target3 = 7
|
||||
val result3 = solution.searchInsert(nums3, target3)
|
||||
val expected3 = 4
|
||||
printTestResult("test case 3:insert at end $target3", assertEquals(result3, expected3))
|
||||
|
||||
// 测试用例 4: 目标值小于所有元素
|
||||
|
||||
val nums4 = intArrayOf(1, 3, 5, 6)
|
||||
val target4 = 0
|
||||
val result4 = solution.searchInsert(nums4, target4)
|
||||
val expected4 = 0
|
||||
printTestResult("test case 4:insert at start $target4", assertEquals(result4, expected4))
|
||||
|
||||
println("\n all test cases passed!")
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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所有测试完成!")
|
||||
|
||||
110
array/1binary search/704Binary search/CMakeLists.txt
Normal file
110
array/1binary search/704Binary search/CMakeLists.txt
Normal file
@@ -0,0 +1,110 @@
|
||||
# 1. 指定CMake最低版本要求
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
# 2. 设置项目信息
|
||||
project(
|
||||
704BinarySearch # 项目名称
|
||||
VERSION 1.0.0 # 项目版本
|
||||
DESCRIPTION "Simple C++ Project"
|
||||
LANGUAGES CXX # 支持的语言
|
||||
)
|
||||
|
||||
# 3. 设置C++标准和编译特性
|
||||
set(CMAKE_CXX_STANDARD 17) # 使用C++17标准
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON) # 必须支持指定标准
|
||||
set(CMAKE_CXX_EXTENSIONS OFF) # 禁用编译器特有扩展
|
||||
|
||||
# 4. 配置构建类型和编译选项
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release) # 默认构建类型为Release
|
||||
endif()
|
||||
|
||||
# 公共编译选项
|
||||
# 修改后 - 分开添加选项
|
||||
add_compile_options(
|
||||
"$<$<CONFIG:Release>:-O3>" # Release模式优化
|
||||
"$<$<CONFIG:Debug>:-g3>"
|
||||
"$<$<CONFIG:Debug>:-O0>"
|
||||
)
|
||||
|
||||
# 平台特定选项
|
||||
if(MSVC)
|
||||
add_compile_options(/W4 /WX) # MSVC: 警告等级4,视警告为错误
|
||||
else()
|
||||
add_compile_options(-Wall -Wextra -Wpedantic -Werror) # GCC/Clang: 严格警告
|
||||
endif()
|
||||
|
||||
# 5. 查找依赖包
|
||||
# find_package(Boost 1.70 COMPONENTS filesystem system)
|
||||
|
||||
# 6. 包含目录设置
|
||||
include_directories(
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include # 项目头文件目录
|
||||
)
|
||||
|
||||
# 7. 源文件收集
|
||||
file(GLOB_RECURSE SOURCES "src/*.cpp") # 递归收集源文件
|
||||
file(GLOB_RECURSE HEADERS "include/*.h") # 头文件
|
||||
|
||||
# 8. 创建目标
|
||||
# 可执行文件目标
|
||||
add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})
|
||||
|
||||
# 9. 链接依赖库
|
||||
if(Boost_FOUND)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PRIVATE
|
||||
Boost::filesystem
|
||||
Boost::system
|
||||
)
|
||||
endif()
|
||||
|
||||
# 10. 安装规则
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
RUNTIME DESTINATION bin
|
||||
LIBRARY DESTINATION lib
|
||||
ARCHIVE DESTINATION lib
|
||||
)
|
||||
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
|
||||
# 11. 测试支持
|
||||
enable_testing()
|
||||
|
||||
# 12. 附加功能
|
||||
# 12.1 Windows资源文件
|
||||
if(WIN32 AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/app.rc)
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/app.rc)
|
||||
endif()
|
||||
|
||||
# # 12.2 预编译头文件
|
||||
# target_precompile_headers(${PROJECT_NAME} PRIVATE
|
||||
# <vector>
|
||||
# <string>
|
||||
# <memory>
|
||||
# ${PROJECT_SOURCE_DIR}/include/pch.h
|
||||
# )
|
||||
|
||||
# 13. 生成配置文件
|
||||
# 13.1 导出头文件路径
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# 13.2 生成版本信息
|
||||
configure_file(
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/cmake/Version.hpp.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/Version.hpp
|
||||
)
|
||||
|
||||
# 14. 自定义目标
|
||||
add_custom_target(run
|
||||
COMMAND ${PROJECT_NAME}
|
||||
DEPENDS ${PROJECT_NAME}
|
||||
COMMENT "Running ${PROJECT_NAME}..."
|
||||
)
|
||||
|
||||
# 15. 包管理器集成
|
||||
include(CPack)
|
||||
43
array/1binary search/704Binary search/kotlin/704.kt
Normal file
43
array/1binary search/704Binary search/kotlin/704.kt
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
// (版本二)左闭右闭区间
|
||||
class Solution {
|
||||
fun search(nums: IntArray, target: Int): Int {
|
||||
var left = 0
|
||||
var right = nums.size - 1 // [left,right] 右侧为闭区间,right 设置为 nums.size - 1
|
||||
while (left <= right) {
|
||||
val mid = (left + right) / 2
|
||||
if (nums[mid] < target) left = mid + 1
|
||||
else if (nums[mid] > target) right = mid - 1 // 代码的核心,循环中 right 是闭区间,这里也应是闭区间
|
||||
else return mid
|
||||
}
|
||||
return -1 // 没有找到 target ,返回 -1
|
||||
}
|
||||
}
|
||||
|
||||
class Solution_2 {
|
||||
|
||||
fun search(nums: IntArray, target: Int): Int {
|
||||
var left = 0
|
||||
var right = nums.size // [left,right) 右侧为开区间,
|
||||
while (left < right) {
|
||||
val mid = (left + right) / 2
|
||||
if (nums[mid] < target) left = mid + 1
|
||||
else if (nums[mid] > target) right = mid // 代码的核心,循环中 right 是开区间,这里应是开区间
|
||||
else return mid
|
||||
}
|
||||
return -1 // 没有找到 target ,返回 -1
|
||||
}
|
||||
}
|
||||
|
||||
// 测试用例
|
||||
fun main() {
|
||||
val nums = intArrayOf( 0, 1, 2, 4, 5, 6, 7)
|
||||
val target = 0
|
||||
val solution = Solution()
|
||||
val result = solution.search(nums, target)
|
||||
val solution2 = Solution_2()
|
||||
val result2 = solution2.search(nums, target)
|
||||
println("Solution 1: $result") // 0
|
||||
println("Solution 2: $result2") // 0
|
||||
|
||||
}
|
||||
70
array/1binary search/704Binary search/kotlin/App.kt
Normal file
70
array/1binary search/704Binary search/kotlin/App.kt
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* This Kotlin source file was generated by the Gradle 'init' task.
|
||||
*/
|
||||
package binarySearch
|
||||
|
||||
class Solution {
|
||||
fun search(nums: IntArray, target: Int): Int {
|
||||
var left = 0
|
||||
var right = nums.size - 1 // [left,right] 右侧为闭区间,right 设置为 nums.size - 1
|
||||
while (left <= right) {
|
||||
val mid = (left + right) / 2
|
||||
if (nums[mid] < target) left = mid + 1
|
||||
else if (nums[mid] > target) right = mid - 1 // 代码的核心,循环中 right 是闭区间,这里也应是闭区间
|
||||
else return mid
|
||||
}
|
||||
return -1 // 没有找到 target ,返回 -1
|
||||
}
|
||||
}
|
||||
|
||||
// 测试用例
|
||||
fun main() {
|
||||
val nums = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8)
|
||||
|
||||
println("请输入要查找的数字:")
|
||||
val input = readLine()
|
||||
|
||||
// 验证输入有效性
|
||||
if (input.isNullOrBlank()) {
|
||||
println("错误:未输入任何内容")
|
||||
return
|
||||
}
|
||||
|
||||
val target = input.toIntOrNull() ?: run {
|
||||
println("错误:请输入有效的整数")
|
||||
return
|
||||
}
|
||||
|
||||
val solution = Solution()
|
||||
val result = solution.search(nums, target)
|
||||
if (result == -1){
|
||||
println("不存在$target")
|
||||
}
|
||||
else{
|
||||
println("目标索引位置: $result")
|
||||
}
|
||||
}
|
||||
|
||||
// fun main() {
|
||||
// val nums = intArrayOf(4, 5, 6, 7, 0, 1, 2)
|
||||
// val reader = System.`in`.bufferedReader()
|
||||
|
||||
// print("请输入要查找的数字: ")
|
||||
// System.out.flush()
|
||||
|
||||
// val input = reader.readLine()
|
||||
|
||||
// if (input.isNullOrBlank()) {
|
||||
// println("错误:未输入任何内容")
|
||||
// return
|
||||
// }
|
||||
|
||||
// val target = input.toIntOrNull() ?: run {
|
||||
// println("错误:请输入有效的整数")
|
||||
// return
|
||||
// }
|
||||
|
||||
// val solution = Solution()
|
||||
// val result = solution.search(nums, target)
|
||||
// println("目标索引位置: $result")
|
||||
// }
|
||||
134
array/1binary search/704Binary search/python/704. 二分查找.ipynb
Normal file
134
array/1binary search/704Binary search/python/704. 二分查找.ipynb
Normal file
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# [704. 二分查找](https://leetcode.cn/problems/binary-search)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 题目描述 \n",
|
||||
"\n",
|
||||
"给定一个 `n` 个元素有序的(升序)整型数组 `nums` 和一个目标值 `target` ,写一个函数搜索 `nums` 中的 `target`,如果 `target` 存在返回下标,否则返回 `-1`。\n",
|
||||
"\n",
|
||||
"你必须编写一个具有 `O(log n)` 时间复杂度的算法。\n",
|
||||
"\n",
|
||||
" \n",
|
||||
"**示例 1:**\n",
|
||||
"\n",
|
||||
"```txt\n",
|
||||
"输入: nums = [-1,0,3,5,9,12], target = 9\n",
|
||||
"输出: 4\n",
|
||||
"解释: 9 出现在 nums 中并且下标为 4\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"**示例 2:**\n",
|
||||
"\n",
|
||||
"```txt\n",
|
||||
"输入: nums = [-1,0,3,5,9,12], target = 2\n",
|
||||
"输出: -1\n",
|
||||
"解释: 2 不存在 nums 中因此返回 -1\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"**提示:**\n",
|
||||
"\n",
|
||||
"1. 你可以假设 `nums` 中的所有元素是不重复的。\n",
|
||||
"2. `n` 将在 `[1, 10000]`之间。\n",
|
||||
"3. `nums` 的每个元素都将在 `[-9999, 9999]`之间。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"---\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 解答"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class Solution(object):\n",
|
||||
" def search(self, nums, target):\n",
|
||||
" \"\"\"\n",
|
||||
" :type nums: List[int]\n",
|
||||
" :type target: int\n",
|
||||
" :rtype: int\n",
|
||||
" \"\"\"\n",
|
||||
" left_location, right_location = 0, len(nums) - 1\n",
|
||||
" while left_location <= right_location:\n",
|
||||
" mid_location = (left_location + right_location) // 2\n",
|
||||
" if nums[mid_location] == target:\n",
|
||||
" return mid_location\n",
|
||||
" elif nums[mid_location] < target:\n",
|
||||
" left_location = mid_location + 1\n",
|
||||
" else:\n",
|
||||
" right_location = mid_location - 1\n",
|
||||
" return -1\n",
|
||||
" "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"id": "6154c8b4",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"1\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"Solution=Solution().search([5, 6, 7, 8, 9, 10], 6) # Example usage\n",
|
||||
"print(Solution) # Output: 1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "6aca97d4",
|
||||
"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
|
||||
}
|
||||
46
array/1binary search/704Binary search/src/704.cpp
Normal file
46
array/1binary search/704Binary search/src/704.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
int search(vector<int> &nums, int target)
|
||||
{
|
||||
left_location = 0;
|
||||
right_location = nums.size() - 1;
|
||||
|
||||
while (left_location <= right_location)
|
||||
{
|
||||
// mid_location = (left_location + right_location) / 2;
|
||||
mid_location = (left_location + right_location) >> 1;
|
||||
if (nums[mid_location] == target)
|
||||
{
|
||||
return mid_location;
|
||||
}
|
||||
else if (nums[mid_location] < target)
|
||||
{
|
||||
left_location = mid_location + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
right_location = mid_location - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private:
|
||||
int left_location, right_location, mid_location;
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
Solution solution;
|
||||
vector<int> nums = {1, 2, 3, 4, 5};
|
||||
int target = 3;
|
||||
int result = solution.search(nums, target);
|
||||
cout << "The index of target in nums is: " << result << endl;
|
||||
system("pause");
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user