feat: Add Dart codes for binary search (#688)

This commit is contained in:
liuyuxin 2023-08-14 23:07:20 +08:00 committed by GitHub
parent c9006c3fe6
commit 4c75c204f3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 108 additions and 0 deletions

View file

@ -0,0 +1,48 @@
/**
* File: binary_search_edge.dart
* Created Time: 2023-08-14
* Author: liuyuxin (gvenusleo@gmail.com)
*/
import 'binary_search_insertion.dart';
/* 二分查找最左一个 target */
int binarySearchLeftEdge(List<int> nums, int target) {
// target
int i = binarySearchInsertion(nums, target);
// target -1
if (i == nums.length || nums[i] != target) {
return -1;
}
// target i
return i;
}
/* 二分查找最右一个 target */
int binarySearchRightEdge(List<int> nums, int target) {
// target + 1
int i = binarySearchInsertion(nums, target + 1);
// j target i target
int j = i - 1;
// target -1
if (j == -1 || nums[j] != target) {
return -1;
}
// target j
return j;
}
/* Driver Code */
void main() {
//
List<int> nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
print("\n数组 nums = $nums");
//
for (int target in [6, 7]) {
int index = binarySearchLeftEdge(nums, target);
print("最左一个元素 $target 的索引为 $index");
index = binarySearchRightEdge(nums, target);
print("最右一个元素 $target 的索引为 $index");
}
}

View file

@ -0,0 +1,60 @@
/**
* File: binary_search_insertion.dart
* Created Time: 2023-08-14
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 二分查找插入点(无重复元素) */
int binarySearchInsertionSimple(List<int> nums, int target) {
int i = 0, j = nums.length - 1; // [0, n-1]
while (i <= j) {
int m = i + (j - i) ~/ 2; // m
if (nums[m] < target) {
i = m + 1; // target [m+1, j]
} else if (nums[m] > target) {
j = m - 1; // target [i, m-1]
} else {
return m; // target m
}
}
// target i
return i;
}
/* 二分查找插入点(存在重复元素) */
int binarySearchInsertion(List<int> nums, int target) {
int i = 0, j = nums.length - 1; // [0, n-1]
while (i <= j) {
int m = i + (j - i) ~/ 2; // m
if (nums[m] < target) {
i = m + 1; // target [m+1, j]
} else if (nums[m] > target) {
j = m - 1; // target [i, m-1]
} else {
j = m - 1; // target [i, m-1]
}
}
// i
return i;
}
/* Driver Code */
void main() {
//
List<int> nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
print("\n数组 nums = $nums");
//
for (int target in [6, 9]) {
int index = binarySearchInsertionSimple(nums, target);
print("元素 $target 的插入点的索引为 $index");
}
//
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
print("\n数组 nums = $nums");
//
for (int target in [2, 6, 20]) {
int index = binarySearchInsertion(nums, target);
print("元素 $target 的插入点的索引为 $index");
}
}