二分必须满足:
- Sorted(单调递增或者递减)
- Bounded(存在上下界)
- Accessible by index(能够通过索引访问)
代码:这个没什么好讲的,应该都明白
class Solution {
fun search(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.size - 1
while (left <= right) {
val mid = left + (right - left) / 2
if (nums[mid] < target) {
left = mid + 1
} else if (nums[mid] > target) {
right = mid - 1
} else if (nums[mid] == target) {
return mid
}
}
return -1
}
}
相关题目:
本站由以下主机服务商提供服务支持:
0条评论