mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-24 18:55:36 +08:00
build
This commit is contained in:
@ -168,8 +168,8 @@ comments: true
|
||||
/* 二分查找(双闭区间) */
|
||||
func binarySearch(nums: [Int], target: Int) -> Int {
|
||||
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
|
||||
var i = 0
|
||||
var j = nums.count - 1
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // 计算中点索引 m
|
||||
@ -466,8 +466,8 @@ comments: true
|
||||
/* 二分查找(左闭右开区间) */
|
||||
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
|
||||
// 初始化左闭右开区间 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
var i = 0
|
||||
var j = nums.count
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while i < j {
|
||||
let m = i + (j - i) / 2 // 计算中点索引 m
|
||||
|
@ -105,7 +105,7 @@ comments: true
|
||||
// 等价于查找 target 的插入点
|
||||
let i = binarySearchInsertion(nums: nums, target: target)
|
||||
// 未找到 target ,返回 -1
|
||||
if i == nums.count || nums[i] != target {
|
||||
if i == nums.endIndex || nums[i] != target {
|
||||
return -1
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
|
@ -140,7 +140,9 @@ comments: true
|
||||
```swift title="binary_search_insertion.swift"
|
||||
/* 二分查找插入点(无重复元素) */
|
||||
func binarySearchInsertionSimple(nums: [Int], target: Int) -> Int {
|
||||
var i = 0, j = nums.count - 1 // 初始化双闭区间 [0, n-1]
|
||||
// 初始化双闭区间 [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // 计算中点索引 m
|
||||
if nums[m] < target {
|
||||
@ -445,7 +447,9 @@ comments: true
|
||||
```swift title="binary_search_insertion.swift"
|
||||
/* 二分查找插入点(存在重复元素) */
|
||||
func binarySearchInsertion(nums: [Int], target: Int) -> Int {
|
||||
var i = 0, j = nums.count - 1 // 初始化双闭区间 [0, n-1]
|
||||
// 初始化双闭区间 [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // 计算中点索引 m
|
||||
if nums[m] < target {
|
||||
|
Reference in New Issue
Block a user