二分查找(下)
Posted 编程加油站
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找(下)相关的知识,希望对你有一定的参考价值。
// 查找第一个等于给定值
const biaryFindFirst = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else if (target > sortedArr[mid]) {
low = mid + 1
} else {
if (mid === 0 || sortedArr[mid - 1] < target) return mid
high = mid - 1
}
}
return -1
}
二、查找最后一个值等于给定值的元素
// 查找最后一个相等的数
const biaryFindLast = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else if (target > sortedArr[mid]) {
low = mid + 1
} else {
if (mid === sortedArr.length - 1 || sortedArr[mid + 1] > target) return mid
low = mid + 1
}
}
return -1
}
三、查找第一个大于等于给定值的元素
const biaryFindFistBig = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target <= sortedArr[mid]) {
if (mid === 0 || sortedArr[mid - 1] < target) return mid
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
四、查找最后一个小于等于给定值的元素
// 查找最后一个小于等于给定值的元素
const biaryFindLastSmall = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else {
if (mid === sortedArr.length - 1 || sortedArr[mid + 1] >= target) return mid
low = mid + 1
}
}
return -1
}
以上是关于二分查找(下)的主要内容,如果未能解决你的问题,请参考以下文章