返回介绍

lcci / 10.05.Sparse Array Search / README_EN

发布于 2024-06-17 01:04:43 字数 3092 浏览 0 评论 0 收藏 0

10.05. Sparse Array Search

Description

Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.

Example1:


 Input: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"

 Output: -1

 Explanation: Return -1 if s is not in words.

Example2:


 Input: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"

 Output: 4

Note:

  1. 1 <= words.length <= 1000000

Solutions

Solution 1

class Solution:
  def findString(self, words: List[str], s: str) -> int:
    left, right = 0, len(words) - 1
    while left < right:
      mid = (left + right) >> 1
      while left < mid and words[mid] == '':
        mid -= 1
      if s <= words[mid]:
        right = mid
      else:
        left = mid + 1
    return -1 if words[left] != s else left
class Solution {
  public int findString(String[] words, String s) {
    int left = 0, right = words.length - 1;
    while (left < right) {
      int mid = (left + right) >> 1;
      while (left < mid && "".equals(words[mid])) {
        --mid;
      }
      if (s.compareTo(words[mid]) <= 0) {
        right = mid;
      } else {
        left = mid + 1;
      }
    }
    return s.equals(words[left]) ? left : -1;
  }
}
class Solution {
public:
  int findString(vector<string>& words, string s) {
    int left = 0, right = words.size() - 1;
    while (left < right) {
      int mid = left + right >> 1;
      while (left < mid && words[mid] == "") --mid;
      if (s <= words[mid])
        right = mid;
      else
        left = mid + 1;
    }
    return words[left] == s ? left : -1;
  }
};
func findString(words []string, s string) int {
  left, right := 0, len(words)-1
  for left < right {
    mid := (left + right) >> 1
    for left < mid && words[mid] == "" {
      mid--
    }
    if s <= words[mid] {
      right = mid
    } else {
      left = mid + 1
    }
  }
  if words[left] == s {
    return left
  }
  return -1
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文