您当前的位置: 首页 >  搜索

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

稀疏数组搜索

IT之一小佬 发布时间:2021-07-25 22:00:21 ,浏览量:0

稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。

示例1:

 输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
 输出:-1
 说明: 不存在返回-1。

示例2:

 输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
 输出:4

示例代码1:

class Solution(object):
    def findString(self, words, s):
        """
        :type words: List[str]
        :type s: str
        :rtype: int
        """
        location = 0
        for i in words:
            if i == s:
                return location
            location += 1
        return -1

示例代码2:

class Solution(object):
    def findString(self, words, s):
        """
        :type words: List[str]
        :type s: str
        :rtype: int
        """
        try:
            res = words.index(s)
        except:
            res = -1
        return res

思路解析:

如果直接return words.index(s), s不存在时会出错 所以try...except,捕获到错误时,返回-1

示例代码3(二分查找):

class Solution(object):
    def findString(self, words, s):
        """
        :type words: List[str]
        :type s: str
        :rtype: int
        """
        a, b = 0, len(words) - 1  # 左右指针
        mid = (a+b) // 2  # 初始化
        while a             
关注
打赏
1665675218
查看更多评论
0.0472s