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

Binary Search Algorithm All In One

Binary Search Algorithm All In One

二分搜索算法

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



167. 两数之和 II - 输入有序数组

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/

https://leetcode-solution-leetcode-pp.gitbook.io/leetcode-solution/easy/167.two-sum-ii-input-array-is-sorted

Big O

refs

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

https://replit.com/@xgqfrms/PPLabs-frontend-answers

blogs

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



©xgqfrms 2012-2020

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

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2019-08-22 09:24  xgqfrms  阅读(59)  评论(9编辑  收藏  举报