This commit is contained in:
krahets
2023-10-08 01:43:28 +08:00
parent 3d2d669b43
commit baac2d11a7
52 changed files with 999 additions and 625 deletions
+2 -2
View File
@@ -119,7 +119,7 @@ comments: true
```csharp title="binary_search.cs"
/* 二分查找(双闭区间) */
int binarySearch(int[] nums, int target) {
int BinarySearch(int[] nums, int target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
int i = 0, j = nums.Length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
@@ -409,7 +409,7 @@ comments: true
```csharp title="binary_search.cs"
/* 二分查找(左闭右开) */
int binarySearchLCRO(int[] nums, int target) {
int BinarySearchLCRO(int[] nums, int target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
int i = 0, j = nums.Length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
+4 -4
View File
@@ -69,9 +69,9 @@ comments: true
```csharp title="binary_search_edge.cs"
/* 二分查找最左一个 target */
int binarySearchLeftEdge(int[] nums, int target) {
int BinarySearchLeftEdge(int[] nums, int target) {
// 等价于查找 target 的插入点
int i = binary_search_insertion.binarySearchInsertion(nums, target);
int i = binary_search_insertion.BinarySearchInsertion(nums, target);
// 未找到 target ,返回 -1
if (i == nums.Length || nums[i] != target) {
return -1;
@@ -273,9 +273,9 @@ comments: true
```csharp title="binary_search_edge.cs"
/* 二分查找最右一个 target */
int binarySearchRightEdge(int[] nums, int target) {
int BinarySearchRightEdge(int[] nums, int target) {
// 转化为查找最左一个 target + 1
int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1);
// j 指向最右一个 target ,i 指向首个大于 target 的元素
int j = i - 1;
// 未找到 target ,返回 -1
@@ -92,7 +92,7 @@ comments: true
```csharp title="binary_search_insertion.cs"
/* 二分查找插入点(无重复元素) */
int binarySearchInsertionSimple(int[] nums, int target) {
int BinarySearchInsertionSimple(int[] nums, int target) {
int i = 0, j = nums.Length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // 计算中点索引 m
@@ -392,7 +392,7 @@ comments: true
```csharp title="binary_search_insertion.cs"
/* 二分查找插入点(存在重复元素) */
int binarySearchInsertion(int[] nums, int target) {
int BinarySearchInsertion(int[] nums, int target) {
int i = 0, j = nums.Length - 1; // 初始化双闭区间 [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // 计算中点索引 m
@@ -69,7 +69,7 @@ comments: true
```csharp title="two_sum.cs"
/* 方法一:暴力枚举 */
int[] twoSumBruteForce(int[] nums, int target) {
int[] TwoSumBruteForce(int[] nums, int target) {
int size = nums.Length;
// 两层循环,时间复杂度 O(n^2)
for (int i = 0; i < size - 1; i++) {
@@ -306,7 +306,7 @@ comments: true
```csharp title="two_sum.cs"
/* 方法二:辅助哈希表 */
int[] twoSumHashTable(int[] nums, int target) {
int[] TwoSumHashTable(int[] nums, int target) {
int size = nums.Length;
// 辅助哈希表,空间复杂度 O(n)
Dictionary<int, int> dic = new();