增加二分法的变种应用

This commit is contained in:
xuzhiwei 2019-06-15 22:02:52 +09:00
parent de13b81887
commit 2612b9214c

View File

@ -0,0 +1,115 @@
/**
* 使
*
*/
class BinaryFind {
/**
*
* @param array
* @param target
* @return
*/
static findFirstElement(array: number[], target: number): number {
const length = array ? array.length : null
if (!length || length === 0) return -1
let low = 0
let high = length - 1
while (low <= high) {
const mid = low + ((high - low) >> 2)
if (array[mid] > target) {
high = mid - 1
} else if (array[mid] < target) {
low = mid + 1
} else {
if (mid === 0 || array[mid - 1] !== target) {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
/**
*
* @param array
* @param target
*/
static findLastElement(array: number[], target: number): number {
const length = array ? array.length : null
if (!length || length === 0) return -1
let low = 0
let high = length - 1
while (low <= high) {
const mid = low + ((high - low) >> 2)
if (array[mid] > target) {
high = mid - 1
} else if (array[mid] < target) {
low = mid + 1
// 这里已经是找到相等的元素了
} else {
if (mid === length - 1 || array[mid + 1] !== target) {
return mid
} else {
low = mid + 1
}
}
}
return -1
}
/**
*
* @param array
* @param target
*/
static findFirstElementGreaterThanTarget(array: number[], target: number): number {
const length = array ? array.length : null
if (!length || length === 0) return -1
let low = 0
let high = length - 1
while (low <= high) {
const mid = low + ((high - low) >> 2)
if (array[mid] < target) {
low = mid + 1
} else {
if (mid === 0 || array[mid - 1] < target) {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
/**
*
* @param array
* @param target
*/
static findLastElementLessThanTarget(array: number[], target: number): number {
const length = array ? array.length : null
if (!length || length === 0) return -1
let low = 0
let high = length - 1
while (low <= high) {
const mid = low + ((high - low) >> 2)
if (array[mid] > target) {
high = mid - 1
} else {
if (mid === length - 1 || array[mid + 1] > target) {
return mid
} else {
low = mid + 1
}
}
}
return -1
}
}
const binaryFindTest = [1, 3, 4, 4, 5, 6, 8, 8, 8, 11, 18]
const target = BinaryFind.findLastElementLessThanTarget(binaryFindTest, -1)
console.log(target)