mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-29 03:17:13 +00:00
build
This commit is contained in:
@@ -72,17 +72,17 @@ $$
|
||||
|
||||
```cpp title="binary_search.cpp"
|
||||
/* 二分查找(双闭区间) */
|
||||
int binarySearch(vector<int>& nums, int target) {
|
||||
int binarySearch(vector<int> &nums, int target) {
|
||||
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
|
||||
int i = 0, j = nums.size() - 1;
|
||||
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
|
||||
while (i <= j) {
|
||||
int m = (i + j) / 2; // 计算中点索引 m
|
||||
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j] 中
|
||||
int m = (i + j) / 2; // 计算中点索引 m
|
||||
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // 此情况说明 target 在区间 [i, m-1] 中
|
||||
j = m - 1;
|
||||
else // 找到目标元素,返回其索引
|
||||
else // 找到目标元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
// 未找到目标元素,返回 -1
|
||||
@@ -283,17 +283,17 @@ $$
|
||||
|
||||
```cpp title="binary_search.cpp"
|
||||
/* 二分查找(左闭右开) */
|
||||
int binarySearch1(vector<int>& nums, int target) {
|
||||
int binarySearch1(vector<int> &nums, int target) {
|
||||
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
int i = 0, j = nums.size();
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while (i < j) {
|
||||
int m = (i + j) / 2; // 计算中点索引 m
|
||||
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j) 中
|
||||
int m = (i + j) / 2; // 计算中点索引 m
|
||||
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j) 中
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // 此情况说明 target 在区间 [i, m) 中
|
||||
j = m;
|
||||
else // 找到目标元素,返回其索引
|
||||
else // 找到目标元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
// 未找到目标元素,返回 -1
|
||||
|
||||
@@ -149,7 +149,7 @@ comments: true
|
||||
|
||||
```cpp title="hashing_search.cpp"
|
||||
/* 哈希查找(链表) */
|
||||
ListNode* hashingSearchLinkedList(unordered_map<int, ListNode*> map, int target) {
|
||||
ListNode *hashingSearchLinkedList(unordered_map<int, ListNode *> map, int target) {
|
||||
// 哈希表的 key: 目标节点值,value: 节点对象
|
||||
// 若哈希表中无此 key ,返回 nullptr
|
||||
if (map.find(target) == map.end())
|
||||
|
||||
@@ -34,7 +34,7 @@ comments: true
|
||||
|
||||
```cpp title="linear_search.cpp"
|
||||
/* 线性查找(数组) */
|
||||
int linearSearchArray(vector<int>& nums, int target) {
|
||||
int linearSearchArray(vector<int> &nums, int target) {
|
||||
// 遍历数组
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
// 找到目标元素,返回其索引
|
||||
@@ -190,7 +190,7 @@ comments: true
|
||||
|
||||
```cpp title="linear_search.cpp"
|
||||
/* 线性查找(链表) */
|
||||
ListNode* linearSearchLinkedList(ListNode* head, int target) {
|
||||
ListNode *linearSearchLinkedList(ListNode *head, int target) {
|
||||
// 遍历链表
|
||||
while (head != nullptr) {
|
||||
// 找到目标节点,返回之
|
||||
|
||||
Reference in New Issue
Block a user