Refactor the section of bianry search.

This commit is contained in:
krahets
2023-05-21 04:51:32 +08:00
parent 921d87c238
commit c3e7455285
22 changed files with 76 additions and 161 deletions

View File

@ -11,7 +11,7 @@ func binarySearch(nums: [Int], target: Int) -> Int {
var j = nums.count - 1
// i > j
while i <= j {
let m = (i + j) / 2 // m
let m = i + (j - i) / 2 // m
if nums[m] < target { // target [m+1, j]
i = m + 1
} else if nums[m] > target { // target [i, m-1]
@ -31,7 +31,7 @@ func binarySearchLCRO(nums: [Int], target: Int) -> Int {
var j = nums.count
// i = j
while i < j {
let m = (i + j) / 2 // m
let m = i + (j - i) / 2 // m
if nums[m] < target { // target [m+1, j)
i = m + 1
} else if nums[m] > target { // target [i, m)