数据结构与算法:在有序但含有空的数组中查找字符串(javascript)

334 阅读1分钟
// 在有序但含有空的数组中查找字符串

// 【题目】

// 给定一个字符串数组strs[],在strs中有些位置为null,但在不为null的位置上,其字符串是按照字典顺序由小到大依次出现的。再给定一个字符串str,请返回str在strs中出现的最左的位置。

// 【举例】

// strs = [null, "a", null, "a", null, "b", null, "c"], str = "a", 返回1。
// strs = [null, "a", null, "a", null, "b", null, "c"], 只要str 为null, 返回-1。
// strs = [null, "a", null, "a", null, "b", null, "c"], str = "d", 返回-1。

// 二分法
const strs = [null, null, "a", "a", null, "a", null, "b", null, "c"];
const getIndex = (arr, str) => {
  if (str === null) {
    return -1;
  }
  let start = 0;
  let end = strs.length - 1;
  while (start < end) {
    let mid = Math.floor((start + end) / 2);
    let m = mid;
    let res = -1;
    while (m >= 0) {
      if (strs[m] !== null) {
        if (strs[m] === str) {
          res = m;
          m--;
        } else if (strs[m] > str) {
          end = m - 1;
          break;
        } else {
          if (res !== -1) {
            return res;
          }
          start = mid + 1;

          break;
        }
      } else {
        m--;
      }
    }
    if (m === -1) {
      if (res !== -1) {
        return res;
      } else {
        return -1;
      }
    }
  }
  if (strs[start] === null) {
    return -1;
  } else {
    if (str === strs[start]) {
      return start;
    } else {
      return -1;
    }
  }
};

console.log(getIndex(strs, "a"));