Compare commits
8 commits
f3ae26d5d9
...
7b7b40ee18
Author | SHA1 | Date | |
---|---|---|---|
|
7b7b40ee18 | ||
|
dad0a3fd95 | ||
|
d11b140ef4 | ||
|
76be14bbd8 | ||
|
3e44192780 | ||
|
6abf0fbdf1 | ||
|
72c7809275 | ||
|
5f77ed363f |
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
@ -30,9 +30,9 @@
|
|||
|
||||
## 致谢
|
||||
|
||||
本书在开源社区众多贡献者的共同努力下不断完善。感谢每一位投入时间与精力的撰稿人,他们是(按照 GitHub 自动生成的顺序):krahets、Gonglja、nuomi1、codingonion、Reanon、justin-tse、hpstory、danielsss、curtishd、night-cruise、S-N-O-R-L-A-X、msk397、gvenusleo、RiverTwilight、gyt95、zhuoqinyue、Zuoxun、mingXta、hello-ikun、khoaxuantu、FangYuan33、GN-Yu、longsizhuo、mgisr、Cathay-Chen、guowei-gong、xBLACKICEx、K3v123、IsChristina、JoseHung、qualifier1024、pengchzn、Guanngxu、QiLOL、L-Super、WSL0809、Slone123c、lhxsm、yuan0221、what-is-me、rongyi、JeffersonHuang、longranger2、theNefelibatas、yuelinxin、xiongsp、nanlei、a16su、cy-by-side、gaofer、malone6、Wonderdch、hongyun-robot、XiaChuerwu、yd-j、bluebean-cloud、iron-irax、he-weilai、Nigh、MolDuM、Phoenix0415、XC-Zero、SamJin98、reeswell、NI-SW、Horbin-Magician、xjr7670、YangXuanyi、DullSword、iStig、qq909244296、jiaxianhua、wenjianmin、keshida、kilikilikid、lclc6、lwbaptx、luluxia、boloboloda、hts0000、gledfish、fbigm、echo1937、szu17dmy、dshlstarr、coderlef、czruby、beintentional、KeiichiKasai、xb534、ElaBosak233、baagod、zhouLion、yishangzhang、yi427、yabo083、weibk、wangwang105、th1nk3r-ing、tao363、4yDX3906、syd168、siqyka、selear、sdshaoda、noobcodemaker、chadyi、lyl625760、lucaswangdev、liuxjerry、0130w、shanghai-Jerry、JackYang-hellobobo、Javesun99、lipusheng、ShiMaRing、FreddieLi、FloranceYeh、Transmigration-zhou、fanchenggang、gltianwen、Dr-XYZ、curly210102、CuB3y0nd、youshaoXG、bubble9um、fanenr、52coder、foursevenlove、KorsChen、ZongYangL、hezhizhen、linzeyan、ZJKung、GaochaoZhu、yang-le、Evilrabbit520、Turing-1024-Lee、Suremotoo、Allen-Scai、Richard-Zhang1019、qingpeng9802、primexiao、nidhoggfgg、1ch0、MwumLi、ZnYang2018、hugtyftg、logan-qiu、psychelzh 和 Keynman 。
|
||||
本书在开源社区众多贡献者的共同努力下不断完善。感谢每一位投入时间与精力的撰稿人,他们是(按照 GitHub 自动生成的顺序):krahets、coderonion、Gonglja、nuomi1、Reanon、justin-tse、hpstory、danielsss、curtishd、night-cruise、S-N-O-R-L-A-X、msk397、gvenusleo、khoaxuantu、RiverTwilight、rongyi、gyt95、zhuoqinyue、K3v123、Zuoxun、mingXta、hello-ikun、FangYuan33、GN-Yu、yuelinxin、longsizhuo、Cathay-Chen、guowei-gong、xBLACKICEx、IsChristina、JoseHung、qualifier1024、QiLOL、pengchzn、Guanngxu、L-Super、WSL0809、Slone123c、lhxsm、yuan0221、what-is-me、theNefelibatas、longranger2、cy-by-side、xiongsp、JeffersonHuang、Transmigration-zhou、magentaqin、Wonderdch、malone6、xiaomiusa87、gaofer、bluebean-cloud、a16su、Shyam-Chen、nanlei、hongyun-robot、Phoenix0415、MolDuM、Nigh、he-weilai、junminhong、mgisr、iron-irax、yd-j、XiaChuerwu、XC-Zero、seven1240、SamJin98、wodray、reeswell、NI-SW、Horbin-Magician、Enlightenus、xjr7670、YangXuanyi、DullSword、boloboloda、iStig、qq909244296、jiaxianhua、wenjianmin、keshida、kilikilikid、lclc6、lwbaptx、liuxjerry、lucaswangdev、lyl625760、hts0000、gledfish、fbigm、echo1937、szu17dmy、dshlstarr、Yucao-cy、coderlef、czruby、bongbongbakudan、beintentional、ZongYangL、ZhongYuuu、luluxia、xb534、bitsmi、ElaBosak233、baagod、zhouLion、yishangzhang、yi427、yabo083、weibk、wangwang105、th1nk3r-ing、tao363、4yDX3906、syd168、steventimes、sslmj2020、smilelsb、siqyka、selear、sdshaoda、Xi-Row、popozhu、nuquist19、noobcodemaker、XiaoK29、chadyi、ZhongGuanbin、shanghai-Jerry、JackYang-hellobobo、Javesun99、lipusheng、BlindTerran、ShiMaRing、FreddieLi、FloranceYeh、iFleey、fanchenggang、gltianwen、goerll、Dr-XYZ、nedchu、curly210102、CuB3y0nd、KraHsu、CarrotDLaw、youshaoXG、bubble9um、fanenr、eagleanurag、LifeGoesOnionOnionOnion、52coder、foursevenlove、KorsChen、hezhizhen、linzeyan、ZJKung、GaochaoZhu、hopkings2008、yang-le、Evilrabbit520、Turing-1024-Lee、thomasq0、Suremotoo、Allen-Scai、Risuntsy、Richard-Zhang1019、qingpeng9802、primexiao、nidhoggfgg、1ch0、MwumLi、martinx、ZnYang2018、hugtyftg、logan-qiu、psychelzh、Keynman、KeiichiKasai 和 0130w。
|
||||
|
||||
本书的代码审阅工作由 codingonion、curtishd、Gonglja、gvenusleo、hpstory、justin-tse、khoaxuantu、krahets、night-cruise、nuomi1 和 Reanon 完成(按照首字母顺序排列)。感谢他们付出的时间与精力,正是他们确保了各语言代码的规范与统一。
|
||||
本书的代码审阅工作由 coderonion、curtishd、Gonglja、gvenusleo、hpstory、justin-tse、khoaxuantu、krahets、night-cruise、nuomi1、Reanon 和 rongyi 完成(按照首字母顺序排列)。感谢他们付出的时间与精力,正是他们确保了各语言代码的规范与统一。
|
||||
|
||||
在本书的创作过程中,我得到了许多人的帮助。
|
||||
|
||||
|
|
|
@ -258,9 +258,9 @@
|
|||
<h3>代码审阅者</h3>
|
||||
<div class="profile-div">
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/codingonion">
|
||||
<img class="profile-img" src="assets/avatar/avatar_codingonion.jpg" alt="Reviewer: codingonion" />
|
||||
<br><b>codingonion</b>
|
||||
<a href="https://github.com/coderonion">
|
||||
<img class="profile-img" src="assets/avatar/avatar_coderonion.jpg" alt="Reviewer: coderonion" />
|
||||
<br><b>coderonion</b>
|
||||
<br><sub>Zig, Rust</sub>
|
||||
</a>
|
||||
</div>
|
||||
|
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 12 KiB |
|
@ -30,9 +30,9 @@ The main content of the book is shown in the figure below.
|
|||
|
||||
## Acknowledgements
|
||||
|
||||
This book is continuously improved with the joint efforts of many contributors from the open-source community. Thanks to each writer who invested their time and energy, listed in the order generated by GitHub: krahets, codingonion, nuomi1, Gonglja, Reanon, justin-tse, danielsss, hpstory, S-N-O-R-L-A-X, night-cruise, msk397, gvenusleo, RiverTwilight, gyt95, zhuoqinyue, Zuoxun, Xia-Sang, mingXta, FangYuan33, GN-Yu, IsChristina, xBLACKICEx, guowei-gong, Cathay-Chen, mgisr, JoseHung, qualifier1024, pengchzn, Guanngxu, longsizhuo, L-Super, what-is-me, yuan0221, lhxsm, Slone123c, WSL0809, longranger2, theNefelibatas, xiongsp, JeffersonHuang, hongyun-robot, K3v123, yuelinxin, a16su, gaofer, malone6, Wonderdch, xjr7670, DullSword, Horbin-Magician, NI-SW, reeswell, XC-Zero, XiaChuerwu, yd-j, iron-irax, huawuque404, MolDuM, Nigh, KorsChen, foursevenlove, 52coder, bubble9um, youshaoXG, curly210102, gltianwen, fanchenggang, Transmigration-zhou, FloranceYeh, FreddieLi, ShiMaRing, lipusheng, Javesun99, JackYang-hellobobo, shanghai-Jerry, 0130w, Keynman, psychelzh, logan-qiu, ZnYang2018, MwumLi, 1ch0, Phoenix0415, qingpeng9802, Richard-Zhang1019, QiLOL, Suremotoo, Turing-1024-Lee, Evilrabbit520, GaochaoZhu, ZJKung, linzeyan, hezhizhen, ZongYangL, beintentional, czruby, coderlef, dshlstarr, szu17dmy, fbigm, gledfish, hts0000, boloboloda, iStig, jiaxianhua, wenjianmin, keshida, kilikilikid, lclc6, lwbaptx, liuxjerry, lucaswangdev, lyl625760, chadyi, noobcodemaker, selear, siqyka, syd168, 4yDX3906, tao363, wangwang105, weibk, yabo083, yi427, yishangzhang, zhouLion, baagod, ElaBosak233, xb534, luluxia, yanedie, thomasq0, YangXuanyi and th1nk3r-ing.
|
||||
This book is continuously improved with the joint efforts of many contributors from the open-source community. Thanks to each writer who invested their time and energy, listed in the order generated by GitHub: krahets, coderonion, Gonglja, nuomi1, Reanon, justin-tse, hpstory, danielsss, curtishd, night-cruise, S-N-O-R-L-A-X, msk397, gvenusleo, khoaxuantu, RiverTwilight, rongyi, gyt95, zhuoqinyue, K3v123, Zuoxun, mingXta, hello-ikun, FangYuan33, GN-Yu, yuelinxin, longsizhuo, Cathay-Chen, guowei-gong, xBLACKICEx, IsChristina, JoseHung, qualifier1024, QiLOL, pengchzn, Guanngxu, L-Super, WSL0809, Slone123c, lhxsm, yuan0221, what-is-me, theNefelibatas, longranger2, cy-by-side, xiongsp, JeffersonHuang, Transmigration-zhou, magentaqin, Wonderdch, malone6, xiaomiusa87, gaofer, bluebean-cloud, a16su, Shyam-Chen, nanlei, hongyun-robot, Phoenix0415, MolDuM, Nigh, he-weilai, junminhong, mgisr, iron-irax, yd-j, XiaChuerwu, XC-Zero, seven1240, SamJin98, wodray, reeswell, NI-SW, Horbin-Magician, Enlightenus, xjr7670, YangXuanyi, DullSword, boloboloda, iStig, qq909244296, jiaxianhua, wenjianmin, keshida, kilikilikid, lclc6, lwbaptx, liuxjerry, lucaswangdev, lyl625760, hts0000, gledfish, fbigm, echo1937, szu17dmy, dshlstarr, Yucao-cy, coderlef, czruby, bongbongbakudan, beintentional, ZongYangL, ZhongYuuu, luluxia, xb534, bitsmi, ElaBosak233, baagod, zhouLion, yishangzhang, yi427, yabo083, weibk, wangwang105, th1nk3r-ing, tao363, 4yDX3906, syd168, steventimes, sslmj2020, smilelsb, siqyka, selear, sdshaoda, Xi-Row, popozhu, nuquist19, noobcodemaker, XiaoK29, chadyi, ZhongGuanbin, shanghai-Jerry, JackYang-hellobobo, Javesun99, lipusheng, BlindTerran, ShiMaRing, FreddieLi, FloranceYeh, iFleey, fanchenggang, gltianwen, goerll, Dr-XYZ, nedchu, curly210102, CuB3y0nd, KraHsu, CarrotDLaw, youshaoXG, bubble9um, fanenr, eagleanurag, LifeGoesOnionOnionOnion, 52coder, foursevenlove, KorsChen, hezhizhen, linzeyan, ZJKung, GaochaoZhu, hopkings2008, yang-le, Evilrabbit520, Turing-1024-Lee, thomasq0, Suremotoo, Allen-Scai, Risuntsy, Richard-Zhang1019, qingpeng9802, primexiao, nidhoggfgg, 1ch0, MwumLi, martinx, ZnYang2018, hugtyftg, logan-qiu, psychelzh, Keynman, KeiichiKasai and 0130w.
|
||||
|
||||
The code review work for this book was completed by codingonion, Gonglja, gvenusleo, hpstory, justin‐tse, khoaxuantu, krahets, night-cruise, nuomi1, and Reanon (listed in alphabetical order). Thanks to them for their time and effort, ensuring the standardization and uniformity of the code in various languages.
|
||||
The code review work for this book was completed by coderonion, Gonglja, gvenusleo, hpstory, justin‐tse, khoaxuantu, krahets, night-cruise, nuomi1, Reanon and rongyi (listed in alphabetical order). Thanks to them for their time and effort, ensuring the standardization and uniformity of the code in various languages.
|
||||
|
||||
Throughout the creation of this book, numerous individuals provided invaluable assistance, including but not limited to:
|
||||
|
||||
|
|
|
@ -6,9 +6,9 @@
|
|||
|
||||
Given a sorted array `nums` of length $n$, which may contain duplicate elements, return the index of the leftmost element `target`. If the element is not present in the array, return $-1$.
|
||||
|
||||
Recall the method of binary search for an insertion point, after the search is completed, $i$ points to the leftmost `target`, **thus searching for the insertion point is essentially searching for the index of the leftmost `target`**.
|
||||
Look back on the method of binary search for an insertion point, after the search is completed, the index $i$ will point to the leftmost occurrence of `target`. Therefore, **searching for the insertion point is essentially the same as finding the index of the leftmost `target`**.
|
||||
|
||||
Consider implementing the search for the left boundary using the function for finding an insertion point. Note that the array might not contain `target`, which could lead to the following two results:
|
||||
We can use the function for finding an insertion point to find the left boundary of `target`. Note that the array might not contain `target`, which could lead to the following two results:
|
||||
|
||||
- The index $i$ of the insertion point is out of bounds.
|
||||
- The element `nums[i]` is not equal to `target`.
|
||||
|
@ -21,27 +21,27 @@ In these cases, simply return $-1$. The code is as follows:
|
|||
|
||||
## Find the right boundary
|
||||
|
||||
So how do we find the rightmost `target`? The most straightforward way is to modify the code, replacing the pointer contraction operation in the case of `nums[m] == target`. The code is omitted here, but interested readers can implement it on their own.
|
||||
How do we find the rightmost occurrence of `target`? The most straightforward way is to modify the traditional binary search logic by changing how we adjust the search boundaries in the case of `nums[m] == target`. The code is omitted here. If you are interested, try to implement the code on your own.
|
||||
|
||||
Below we introduce two more cunning methods.
|
||||
Below we are going to introduce two more ingenious methods.
|
||||
|
||||
### Reusing the search for the left boundary
|
||||
### Reuse the left boundary search
|
||||
|
||||
In fact, we can use the function for finding the leftmost element to find the rightmost element, specifically by **transforming the search for the rightmost `target` into a search for the leftmost `target + 1`**.
|
||||
To find the rightmost occurrence of `target`, we can reuse the logic for finding the leftmost occurrence of `target`. Specifically, we can find the leftmost `target`, and then adjust the result to point to the rightmost `target` by simply adding 1 to the index of the leftmost `target`.
|
||||
|
||||
As shown in the figure below, after the search is completed, the pointer $i$ points to the leftmost `target + 1` (if it exists), while $j$ points to the rightmost `target`, **thus returning $j$ is sufficient**.
|
||||
As shown in the figure below, after the search is complete, pointer $i$ will point to the the position just after the leftmost `target` (i.e., `target + 1`), and pointer $j$ will point to the rightmost `target`. Therefore, returning $j$ will give us the right boundary.
|
||||
|
||||
![Transforming the search for the right boundary into the search for the left boundary](binary_search_edge.assets/binary_search_right_edge_by_left_edge.png)
|
||||
|
||||
Please note, the insertion point returned is $i$, therefore, it should be subtracted by $1$ to obtain $j$:
|
||||
Note that the insertion point returned is $i$, therefore, it should be subtracted by $1$ to obtain $j$:
|
||||
|
||||
```src
|
||||
[file]{binary_search_edge}-[class]{}-[func]{binary_search_right_edge}
|
||||
```
|
||||
|
||||
### Transforming into an element search
|
||||
### Transform into an element search
|
||||
|
||||
We know that when the array does not contain `target`, $i$ and $j$ will eventually point to the first element greater and smaller than `target` respectively.
|
||||
When the array does not contain `target`, $i$ and $j$ will eventually point to the first element greater and smaller than `target` respectively.
|
||||
|
||||
Thus, as shown in the figure below, we can construct an element that does not exist in the array, to search for the left and right boundaries.
|
||||
|
||||
|
@ -50,7 +50,7 @@ Thus, as shown in the figure below, we can construct an element that does not ex
|
|||
|
||||
![Transforming the search for boundaries into the search for an element](binary_search_edge.assets/binary_search_edge_by_element.png)
|
||||
|
||||
The code is omitted here, but two points are worth noting.
|
||||
The code is omitted here, but here are two important points to note about this approach.
|
||||
|
||||
- The given array does not contain decimals, meaning we do not need to worry about how to handle equal situations.
|
||||
- Since this method introduces decimals, the variable `target` in the function needs to be changed to a floating point type (no change needed in Python).
|
||||
- Since the given array does not contain decimals, this means we do not need to worry about handling equal cases.
|
||||
- Because this method introduces decimals, the variable `target` in the function needs to be changed to a floating point type (no change needed in Python).
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Binary search insertion
|
||||
# Binary search for insertion point
|
||||
|
||||
Binary search is not only used to search for target elements but also to solve many variant problems, such as searching for the insertion position of target elements.
|
||||
|
||||
|
@ -6,21 +6,21 @@ Binary search is not only used to search for target elements but also to solve m
|
|||
|
||||
!!! question
|
||||
|
||||
Given an ordered array `nums` of length $n$ and an element `target`, where the array has no duplicate elements. Now insert `target` into the array `nums` while maintaining its order. If the element `target` already exists in the array, insert it to its left side. Please return the index of `target` in the array after insertion. See the example shown in the figure below.
|
||||
Given a sorted array `nums` of length $n$ with unique elements and an element `target`, insert `target` into `nums` while maintaining its sorted order. If `target` already exists in the array, insert it to the left of the existing element. Return the index of `target` in the array after insertion. See the example shown in the figure below.
|
||||
|
||||
![Example data for binary search insertion point](binary_search_insertion.assets/binary_search_insertion_example.png)
|
||||
|
||||
If you want to reuse the binary search code from the previous section, you need to answer the following two questions.
|
||||
|
||||
**Question one**: When the array contains `target`, is the insertion point index the index of that element?
|
||||
**Question one**: If the array already contains `target`, would the insertion point be the index of existing element?
|
||||
|
||||
The requirement to insert `target` to the left of equal elements means that the newly inserted `target` replaces the original `target` position. Thus, **when the array contains `target`, the insertion point index is the index of that `target`**.
|
||||
The requirement to insert `target` to the left of equal elements means that the newly inserted `target` will replace the original `target` position. In other words, **when the array contains `target`, the insertion point is indeed the index of that `target`**.
|
||||
|
||||
**Question two**: When the array does not contain `target`, what is the index of the insertion point?
|
||||
**Question two**: When the array does not contain `target`, at which index would it be inserted?
|
||||
|
||||
Further consider the binary search process: when `nums[m] < target`, pointer $i$ moves, meaning that pointer $i$ is approaching an element greater than or equal to `target`. Similarly, pointer $j$ is always approaching an element less than or equal to `target`.
|
||||
Let's further consider the binary search process: when `nums[m] < target`, pointer $i$ moves, meaning that pointer $i$ is approaching an element greater than or equal to `target`. Similarly, pointer $j$ is always approaching an element less than or equal to `target`.
|
||||
|
||||
Therefore, at the end of the binary, it is certain that: $i$ points to the first element greater than `target`, and $j$ points to the first element less than `target`. **It is easy to see that when the array does not contain `target`, the insertion index is $i$**. The code is as follows:
|
||||
Therefore, at the end of the binary, it is certain that: $i$ points to the first element greater than `target`, and $j$ points to the first element less than `target`. **It is easy to see that when the array does not contain `target`, the insertion point is $i$**. The code is as follows:
|
||||
|
||||
```src
|
||||
[file]{binary_search_insertion}-[class]{}-[func]{binary_search_insertion_simple}
|
||||
|
@ -32,21 +32,21 @@ Therefore, at the end of the binary, it is certain that: $i$ points to the first
|
|||
|
||||
Based on the previous question, assume the array may contain duplicate elements, all else remains the same.
|
||||
|
||||
Suppose there are multiple `target`s in the array, ordinary binary search can only return the index of one of the `target`s, **and it cannot determine how many `target`s are to the left and right of that element**.
|
||||
When there are multiple occurrences of `target` in the array, a regular binary search can only return the index of one occurrence of `target`, **and it cannot determine how many occurrences of `target` are to the left and right of that position**.
|
||||
|
||||
The task requires inserting the target element to the very left, **so we need to find the index of the leftmost `target` in the array**. Initially consider implementing this through the steps shown in the figure below.
|
||||
The problem requires inserting the target element to the very left, **so we need to find the index of the leftmost `target` in the array**. Initially consider implementing this through the steps shown in the figure below.
|
||||
|
||||
1. Perform a binary search, get an arbitrary index of `target`, denoted as $k$.
|
||||
2. Start from index $k$, and perform a linear search to the left until the leftmost `target` is found and return.
|
||||
1. Perform a binary search to find any `target`'s index, say $k$.
|
||||
2. Starting from index $k$, perform a linear search to the left until the leftmost `target` is found and return.
|
||||
|
||||
![Linear search for the insertion point of duplicate elements](binary_search_insertion.assets/binary_search_insertion_naive.png)
|
||||
|
||||
Although this method is feasible, it includes linear search, so its time complexity is $O(n)$. This method is inefficient when the array contains many duplicate `target`s.
|
||||
|
||||
Now consider extending the binary search code. As shown in the figure below, the overall process remains the same, each round first calculates the midpoint index $m$, then judges the size relationship between `target` and `nums[m]`, divided into the following cases.
|
||||
Now consider extending the binary search code. As shown in the figure below, the overall process remains the same. In each round, we first calculate the middle index $m$, then compare the value of `target` and `nums[m]`, which results in the following cases.
|
||||
|
||||
- When `nums[m] < target` or `nums[m] > target`, it means `target` has not been found yet, thus use the normal binary search interval reduction operation, **thus making pointers $i$ and $j$ approach `target`**.
|
||||
- When `nums[m] == target`, it indicates that the elements less than `target` are in the interval $[i, m - 1]$, therefore use $j = m - 1$ to narrow the interval, **thus making pointer $j$ approach elements less than `target`**.
|
||||
- When `nums[m] < target` or `nums[m] > target`, it means `target` has not been found yet, thus use the normal binary search to narrow the search range, **bring the pointers $i$ and $j$ closer to `target`**.
|
||||
- When `nums[m] == target`, it indicates that the elements less than `target` are in the range $[i, m - 1]$, therefore use $j = m - 1$ to narrow the range, **thus making pointer $j$ closer to the elements less than `target`**.
|
||||
|
||||
After the loop, $i$ points to the leftmost `target`, and $j$ points to the first element less than `target`, **therefore index $i$ is the insertion point**.
|
||||
|
||||
|
@ -74,9 +74,9 @@ After the loop, $i$ points to the leftmost `target`, and $j$ points to the first
|
|||
=== "<8>"
|
||||
![binary_search_insertion_step8](binary_search_insertion.assets/binary_search_insertion_step8.png)
|
||||
|
||||
Observe the code, the operations of the branch `nums[m] > target` and `nums[m] == target` are the same, so the two can be combined.
|
||||
Observe the following code. The operations in the branches `nums[m] > target` and `nums[m] == target` are the same, so these two branches can be merged.
|
||||
|
||||
Even so, we can still keep the conditions expanded, as their logic is clearer and more readable.
|
||||
Even so, we can still keep the conditions expanded, as it makes the logic clearer and improves readability.
|
||||
|
||||
```src
|
||||
[file]{binary_search_insertion}-[class]{}-[func]{binary_search_insertion}
|
||||
|
@ -84,8 +84,8 @@ Even so, we can still keep the conditions expanded, as their logic is clearer an
|
|||
|
||||
!!! tip
|
||||
|
||||
The code in this section uses "closed intervals". Readers interested can implement the "left-closed right-open" method themselves.
|
||||
The code in this section uses "closed interval". If you are interested in "left-closed,right-open", try to implement the code on your own.
|
||||
|
||||
In summary, binary search is merely about setting search targets for pointers $i$ and $j$, which might be a specific element (like `target`) or a range of elements (like elements less than `target`).
|
||||
In summary, binary search essentially involves setting search targets for pointers $i$ and $j$, which might be a specific element (like `target`) or a range of elements (like elements less than `target`).
|
||||
|
||||
In the continuous loop of binary search, pointers $i$ and $j$ gradually approach the predefined target. Ultimately, they either find the answer or stop after crossing the boundary.
|
||||
In the continuous loop of binary search, pointers $i$ and $j$ gradually approach the predefined target. In the end, they either find the answer or stop after crossing the boundary.
|
||||
|
|
|
@ -258,9 +258,9 @@
|
|||
<h3>Code reviewers</h3>
|
||||
<div class="profile-div">
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/codingonion">
|
||||
<img class="profile-img" src="../assets/avatar/avatar_codingonion.jpg" alt="Reviewer: codingonion" />
|
||||
<br><b>codingonion</b>
|
||||
<a href="https://github.com/coderonion">
|
||||
<img class="profile-img" src="../assets/avatar/avatar_coderonion.jpg" alt="Reviewer: coderonion" />
|
||||
<br><b>coderonion</b>
|
||||
<br><sub>Zig, Rust</sub>
|
||||
</a>
|
||||
</div>
|
||||
|
|
|
@ -117,7 +117,7 @@ nav:
|
|||
# [icon: material/text-search]
|
||||
- chapter_searching/index.md
|
||||
- 10.1 Binary search: chapter_searching/binary_search.md
|
||||
- 10.2 Binary search insertion: chapter_searching/binary_search_insertion.md
|
||||
- 10.2 Binary search for insertion point: chapter_searching/binary_search_insertion.md
|
||||
- 10.3 Binary search boundaries: chapter_searching/binary_search_edge.md
|
||||
- 10.4 Hashing optimization strategies: chapter_searching/replace_linear_by_hashing.md
|
||||
- 10.5 Search algorithms revisited: chapter_searching/searching_algorithm_revisited.md
|
||||
|
|
|
@ -9,7 +9,7 @@ site_dir: site
|
|||
repo_name: krahets/hello-algo
|
||||
repo_url: https://github.com/krahets/hello-algo
|
||||
edit_uri: tree/main/docs
|
||||
version: 1.1.0
|
||||
version: 1.2.0
|
||||
|
||||
# Copyright
|
||||
copyright: Copyright © 2024 krahets<br>The website content is licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>
|
||||
|
|
|
@ -111,16 +111,29 @@ int popLast(ArrayDeque *deque) {
|
|||
return num;
|
||||
}
|
||||
|
||||
/* 返回陣列用於列印 */
|
||||
int *toArray(ArrayDeque *deque, int *queSize) {
|
||||
*queSize = deque->queSize;
|
||||
int *res = (int *)calloc(deque->queSize, sizeof(int));
|
||||
int j = deque->front;
|
||||
for (int i = 0; i < deque->queSize; i++) {
|
||||
res[i] = deque->nums[j % deque->queCapacity];
|
||||
j++;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化佇列 */
|
||||
int capacity = 10;
|
||||
int queSize;
|
||||
ArrayDeque *deque = newArrayDeque(capacity);
|
||||
pushLast(deque, 3);
|
||||
pushLast(deque, 2);
|
||||
pushLast(deque, 5);
|
||||
printf("雙向佇列 deque = ");
|
||||
printArray(deque->nums, deque->queSize);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
|
||||
/* 訪問元素 */
|
||||
int peekFirstNum = peekFirst(deque);
|
||||
|
@ -131,18 +144,18 @@ int main() {
|
|||
/* 元素入列 */
|
||||
pushLast(deque, 4);
|
||||
printf("元素 4 佇列尾入列後 deque = ");
|
||||
printArray(deque->nums, deque->queSize);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
pushFirst(deque, 1);
|
||||
printf("元素 1 佇列首入列後 deque = ");
|
||||
printArray(deque->nums, deque->queSize);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
|
||||
/* 元素出列 */
|
||||
int popLastNum = popLast(deque);
|
||||
printf("佇列尾出列元素 = %d ,佇列尾出列後 deque= ", popLastNum);
|
||||
printArray(deque->nums, deque->queSize);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
int popFirstNum = popFirst(deque);
|
||||
printf("佇列首出列元素 = %d ,佇列首出列後 deque= ", popFirstNum);
|
||||
printArray(deque->nums, deque->queSize);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
int dequeSize = size(deque);
|
||||
|
|
|
@ -74,10 +74,23 @@ int pop(ArrayQueue *queue) {
|
|||
return num;
|
||||
}
|
||||
|
||||
/* 返回陣列用於列印 */
|
||||
int *toArray(ArrayQueue *queue, int *queSize) {
|
||||
*queSize = queue->queSize;
|
||||
int *res = (int *)calloc(queue->queSize, sizeof(int));
|
||||
int j = queue->front;
|
||||
for (int i = 0; i < queue->queSize; i++) {
|
||||
res[i] = queue->nums[j % queue->queCapacity];
|
||||
j++;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化佇列 */
|
||||
int capacity = 10;
|
||||
int queSize;
|
||||
ArrayQueue *queue = newArrayQueue(capacity);
|
||||
|
||||
/* 元素入列 */
|
||||
|
@ -87,7 +100,7 @@ int main() {
|
|||
push(queue, 5);
|
||||
push(queue, 4);
|
||||
printf("佇列 queue = ");
|
||||
printArray(queue->nums, queue->queSize);
|
||||
printArray(toArray(queue, &queSize), queSize);
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
int peekNum = peek(queue);
|
||||
|
@ -96,7 +109,7 @@ int main() {
|
|||
/* 元素出列 */
|
||||
peekNum = pop(queue);
|
||||
printf("出列元素 pop = %d ,出列後 queue = ", peekNum);
|
||||
printArray(queue->nums, queue->queSize);
|
||||
printArray(toArray(queue, &queSize), queSize);
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
int queueSize = size(queue);
|
||||
|
@ -111,7 +124,7 @@ int main() {
|
|||
push(queue, i);
|
||||
pop(queue);
|
||||
printf("第 %d 輪入列 + 出列後 queue = ", i);
|
||||
printArray(queue->nums, queue->queSize);
|
||||
printArray(toArray(queue, &queSize), queSize);
|
||||
}
|
||||
|
||||
// 釋放記憶體
|
||||
|
|
Before Width: | Height: | Size: 434 KiB After Width: | Height: | Size: 88 KiB |
Before Width: | Height: | Size: 465 KiB After Width: | Height: | Size: 143 KiB |
Before Width: | Height: | Size: 477 KiB After Width: | Height: | Size: 122 KiB |
|
@ -50,6 +50,7 @@
|
|||
| front of the queue | 队首 | 佇列首 |
|
||||
| rear of the queue | 队尾 | 佇列尾 |
|
||||
| hash table | 哈希表 | 雜湊表 |
|
||||
| hash set | 哈希集合 | 雜湊集合 |
|
||||
| bucket | 桶 | 桶 |
|
||||
| hash function | 哈希函数 | 雜湊函式 |
|
||||
| hash collision | 哈希冲突 | 雜湊衝突 |
|
||||
|
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 13 KiB |
|
@ -30,9 +30,9 @@
|
|||
|
||||
## 致謝
|
||||
|
||||
本書在開源社群眾多貢獻者的共同努力下不斷完善。感謝每一位投入時間與精力的撰稿人,他們是(按照 GitHub 自動生成的順序):krahets、Gonglja、nuomi1、codingonion、Reanon、justin-tse、hpstory、danielsss、curtishd、night-cruise、S-N-O-R-L-A-X、msk397、gvenusleo、RiverTwilight、gyt95、zhuoqinyue、Zuoxun、mingXta、hello-ikun、khoaxuantu、FangYuan33、GN-Yu、longsizhuo、mgisr、Cathay-Chen、guowei-gong、xBLACKICEx、K3v123、IsChristina、JoseHung、qualifier1024、pengchzn、Guanngxu、QiLOL、L-Super、WSL0809、Slone123c、lhxsm、yuan0221、what-is-me、rongyi、JeffersonHuang、longranger2、theNefelibatas、yuelinxin、xiongsp、nanlei、a16su、cy-by-side、gaofer、malone6、Wonderdch、hongyun-robot、XiaChuerwu、yd-j、bluebean-cloud、iron-irax、he-weilai、Nigh、MolDuM、Phoenix0415、XC-Zero、SamJin98、reeswell、NI-SW、Horbin-Magician、xjr7670、YangXuanyi、DullSword、iStig、qq909244296、jiaxianhua、wenjianmin、keshida、kilikilikid、lclc6、lwbaptx、luluxia、boloboloda、hts0000、gledfish、fbigm、echo1937、szu17dmy、dshlstarr、coderlef、czruby、beintentional、KeiichiKasai、xb534、ElaBosak233、baagod、zhouLion、yishangzhang、yi427、yabo083、weibk、wangwang105、th1nk3r-ing、tao363、4yDX3906、syd168、siqyka、selear、sdshaoda、noobcodemaker、chadyi、lyl625760、lucaswangdev、liuxjerry、0130w、shanghai-Jerry、JackYang-hellobobo、Javesun99、lipusheng、ShiMaRing、FreddieLi、FloranceYeh、Transmigration-zhou、fanchenggang、gltianwen、Dr-XYZ、curly210102、CuB3y0nd、youshaoXG、bubble9um、fanenr、52coder、foursevenlove、KorsChen、ZongYangL、hezhizhen、linzeyan、ZJKung、GaochaoZhu、yang-le、Evilrabbit520、Turing-1024-Lee、Suremotoo、Allen-Scai、Richard-Zhang1019、qingpeng9802、primexiao、nidhoggfgg、1ch0、MwumLi、ZnYang2018、hugtyftg、logan-qiu、psychelzh 和 Keynman 。
|
||||
本書在開源社群眾多貢獻者的共同努力下不斷完善。感謝每一位投入時間與精力的撰稿人,他們是(按照 GitHub 自動生成的順序):krahets、coderonion、Gonglja、nuomi1、Reanon、justin-tse、hpstory、danielsss、curtishd、night-cruise、S-N-O-R-L-A-X、msk397、gvenusleo、khoaxuantu、RiverTwilight、rongyi、gyt95、zhuoqinyue、K3v123、Zuoxun、mingXta、hello-ikun、FangYuan33、GN-Yu、yuelinxin、longsizhuo、Cathay-Chen、guowei-gong、xBLACKICEx、IsChristina、JoseHung、qualifier1024、QiLOL、pengchzn、Guanngxu、L-Super、WSL0809、Slone123c、lhxsm、yuan0221、what-is-me、theNefelibatas、longranger2、cy-by-side、xiongsp、JeffersonHuang、Transmigration-zhou、magentaqin、Wonderdch、malone6、xiaomiusa87、gaofer、bluebean-cloud、a16su、Shyam-Chen、nanlei、hongyun-robot、Phoenix0415、MolDuM、Nigh、he-weilai、junminhong、mgisr、iron-irax、yd-j、XiaChuerwu、XC-Zero、seven1240、SamJin98、wodray、reeswell、NI-SW、Horbin-Magician、Enlightenus、xjr7670、YangXuanyi、DullSword、boloboloda、iStig、qq909244296、jiaxianhua、wenjianmin、keshida、kilikilikid、lclc6、lwbaptx、liuxjerry、lucaswangdev、lyl625760、hts0000、gledfish、fbigm、echo1937、szu17dmy、dshlstarr、Yucao-cy、coderlef、czruby、bongbongbakudan、beintentional、ZongYangL、ZhongYuuu、luluxia、xb534、bitsmi、ElaBosak233、baagod、zhouLion、yishangzhang、yi427、yabo083、weibk、wangwang105、th1nk3r-ing、tao363、4yDX3906、syd168、steventimes、sslmj2020、smilelsb、siqyka、selear、sdshaoda、Xi-Row、popozhu、nuquist19、noobcodemaker、XiaoK29、chadyi、ZhongGuanbin、shanghai-Jerry、JackYang-hellobobo、Javesun99、lipusheng、BlindTerran、ShiMaRing、FreddieLi、FloranceYeh、iFleey、fanchenggang、gltianwen、goerll、Dr-XYZ、nedchu、curly210102、CuB3y0nd、KraHsu、CarrotDLaw、youshaoXG、bubble9um、fanenr、eagleanurag、LifeGoesOnionOnionOnion、52coder、foursevenlove、KorsChen、hezhizhen、linzeyan、ZJKung、GaochaoZhu、hopkings2008、yang-le、Evilrabbit520、Turing-1024-Lee、thomasq0、Suremotoo、Allen-Scai、Risuntsy、Richard-Zhang1019、qingpeng9802、primexiao、nidhoggfgg、1ch0、MwumLi、martinx、ZnYang2018、hugtyftg、logan-qiu、psychelzh、Keynman、KeiichiKasai 和 0130w。
|
||||
|
||||
本書的程式碼審閱工作由 codingonion、curtishd、Gonglja、gvenusleo、hpstory、justin-tse、khoaxuantu、krahets、night-cruise、nuomi1 和 Reanon 完成(按照首字母順序排列)。感謝他們付出的時間與精力,正是他們確保了各語言程式碼的規範與統一。
|
||||
本書的程式碼審閱工作由 coderonion、curtishd、Gonglja、gvenusleo、hpstory、justin-tse、khoaxuantu、krahets、night-cruise、nuomi1、Reanon 和 rongyi 完成(按照首字母順序排列)。感謝他們付出的時間與精力,正是他們確保了各語言程式碼的規範與統一。
|
||||
|
||||
在本書的創作過程中,我得到了許多人的幫助。
|
||||
|
||||
|
|
Before Width: | Height: | Size: 386 KiB After Width: | Height: | Size: 106 KiB |
Before Width: | Height: | Size: 386 KiB After Width: | Height: | Size: 74 KiB |
|
@ -258,9 +258,9 @@
|
|||
<h3>程式碼審閱者</h3>
|
||||
<div class="profile-div">
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/codingonion">
|
||||
<img class="profile-img" src="../assets/avatar/avatar_codingonion.jpg" alt="Reviewer: codingonion" />
|
||||
<br><b>codingonion</b>
|
||||
<a href="https://github.com/coderonion">
|
||||
<img class="profile-img" src="../assets/avatar/avatar_coderonion.jpg" alt="Reviewer: coderonion" />
|
||||
<br><b>coderonion</b>
|
||||
<br><sub>Zig, Rust</sub>
|
||||
</a>
|
||||
</div>
|
||||
|
|
|
@ -9,7 +9,7 @@ docs_dir: ../build/zh-hant/docs
|
|||
site_dir: ../site/zh-hant
|
||||
# Repository
|
||||
edit_uri: tree/main/zh-hant/docs
|
||||
version: 1.1.0
|
||||
version: 1.2.0
|
||||
|
||||
# Configuration
|
||||
theme:
|
||||
|
|