Appearance
二分搜索
如果我们要进行搜索的数组是有序的,那么可以使用二分搜索,该算法的复杂度是 O(LogN)
;
通常我们可以使用系统内置的 sort()
方法对数组进行排序,内置的排序算法复杂度一般是 O(NLogN)
。
Code
javascript
function binarySearch(nums, target) {
let left = 0,
right = nums.length - 1,
mid;
while (left <= right) {
mid = Math.floor(left + (right - left) / 2);
let val = nums[mid];
if (val === target) {
return mid;
} else if (val > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
Test Cases
javascript
const { binarySearch } = require('./binarySearch');
describe('binarySearch', () => {
it('case1', () => {
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const target = 8;
expect(binarySearch(nums, target)).toBe(nums[nums.length - 2]);
});
});