xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Binary search algorithm

二分搜索算法

https://www.geeksforgeeks.org/complexity-analysis-of-binary-search/

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2019-08-22
 *
 * @description binary search
 * @augments
 * @example
 * @link
 *
 */

let log = console.log;

// 2.写一个函数,对于一个排好序的数组,如果当中有两个数的和为某个给定的数target,返回true,否则false,时间复杂度O(n)

// supplement
const binarySearch = (arr = [], target, debug = false) => {
    let result = false;
    let temp = [];
    for (let i = 0; i < arr.length; i++) {
        let supplement = ``;
        supplement = target > arr[i] ? target - arr[i] : arr[i] - target;
        if (debug) {
            log(`supplement =`, supplement);
        }
        if (arr.includes(supplement)) {
            if (!temp.includes(supplement)) {
                temp.push(supplement);
            }
        }
    }
    if (temp.length >= 2) {
        result = true;
    }
    if (debug) {
        log(`temp =`, temp);
    }
    return result;
};


log(binarySearch([1,3,5,7,9], 9));
// false
log(binarySearch([1,3,5,7,9], 4));
// true
log(binarySearch([-1,3,5,7,9], 4));
// true



https://en.wikipedia.org/wiki/Binary_search_algorithm

https://www.quora.com/What-is-the-time-complexity-of-binary-search

https://hackernoon.com/what-does-the-time-complexity-o-log-n-actually-mean-45f94bb5bfbf

https://www.geeksforgeeks.org/complexity-analysis-of-binary-search/

https://my.oschina.net/u/2822116/blog/795225

https://blog.csdn.net/ns_code/article/details/24933341

https://hellozhaozheng.github.io/z_post/面试-算法刷题-剑指offer/#42-和为S的两个数字

https://www.jianshu.com/p/e98eb999328b

https://www.cnblogs.com/DOMLX/p/10940636.html

Big O


Flag Counter

©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/11392498.html