顺序搜索

思路径

for循环遍历查找

代码实现


Array.prototype.sequentialSearch = function (n) {
  for (let i = 0; i < this.length; i++) {
    if (this[i] == n) {
      return i;
    }
  }
  return -1
}
const arr = [5, 4, 3, 2, 1];
var result = arr.sequentialSearch(3)
console.log('result', result)

时空复杂度

时间: O(n)
空间: O(1) 没有使用额外的空间

二分搜索

思路径

把数组折成两半

代码实现

    Array.prototype.binarySearch = function (n) {
      let low = 0;
      let high = this.length - 1;
      while (low < high) {
        let mid = Math.floor((low + high) / 2)
        let midElement = this[mid]
        if (n > midElement) {
          low = mid + 1
        } else if (n < midElement) {
          high = mid - 1
        } else {
          return mid;
        }
      }
      return -1;
    }
    const arr = [5, 4, 3, 2, 1];
    var result = arr.binarySearch(3)
    console.log('result', result)

时空复杂度

时间: O(logN)
空间: O(1) 没有使用额外的空间

leetcode:374

猜数字大小

    function guess(guess) {
      if (guess == 6) {
        return 0
      } else if (guess > 6) {
        return -1
      } else {
        return 1
      }
    }
    function guessNumber(n) {
      let low = 1;
      let high = n;
      while (low <= high) {
        let mid = Math.floor((low + high) / 2)
        const res = guess(mid)
        // console.log('mid', mid)
        // console.log('res', res)
        if (mid === 0) {
          return mid
        } else if (res === 1) {
          low = mid + 1
        } else {
          high = mid - 1
        }
      }
    }
    let result = guessNumber(6)
    console.log('result',result);

时空复杂度

时间: O(logN)
空间: O(1) 没有使用额外的空间


渣渣辉
1.3k 声望147 粉丝