Files
flowerstonezl e1006fa09c first init
2026-01-29 17:04:05 +08:00

43 lines
1.4 KiB
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// (版本二)左闭右闭区间
class Solution {
fun search(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.size - 1 // [left,right] 右侧为闭区间right 设置为 nums.size - 1
while (left <= right) {
val mid = (left + right) / 2
if (nums[mid] < target) left = mid + 1
else if (nums[mid] > target) right = mid - 1 // 代码的核心,循环中 right 是闭区间,这里也应是闭区间
else return mid
}
return -1 // 没有找到 target ,返回 -1
}
}
class Solution_2 {
fun search(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.size // [left,right) 右侧为开区间,
while (left < right) {
val mid = (left + right) / 2
if (nums[mid] < target) left = mid + 1
else if (nums[mid] > target) right = mid // 代码的核心,循环中 right 是开区间,这里应是开区间
else return mid
}
return -1 // 没有找到 target ,返回 -1
}
}
// 测试用例
fun main() {
val nums = intArrayOf( 0, 1, 2, 4, 5, 6, 7)
val target = 0
val solution = Solution()
val result = solution.search(nums, target)
val solution2 = Solution_2()
val result2 = solution2.search(nums, target)
println("Solution 1: $result") // 0
println("Solution 2: $result2") // 0
}