在有序但含有空的数组中查找字符串

在有序但含有空的数组中查找字符串

有序含空数组查找字符串

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

【举例】
strs=[None, “a”, None, “a”, None, “b”, None, “c”], s=“a”, 返回1;
strs=[None, “a”, None, “a”, None, “b”, None, “c”], s=None, 只要s为None, 就返回-1;
strs=[None, “a”, None, “a”, None, “b”, None, “c”], s=“d”, 返回-1;


算法思路

尽量使用二分法查找
遇见None向左遍历直至遇到非None
匹配到s,将索引存储在res中,继续向左二分。
因为要获取s在strs出现的最左位置,此时匹配可能不是最左的结果。


相应代码

# 有序含空数组查找字符串
def index_of_None_strs(arr, s):
    if s is None:
        return -1
    left = 0
    right = len(arr) - 1
    res = -1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == s:
            res = mid
            right = mid + 1
        elif arr[mid] is None:
            index = mid
            while arr[index] is None:
                index -= 1
            if arr[index] == s:
                res = index
                right = index - 1
            elif arr[index] < s:
                left = mid + 1
            else:
                right = index - 1
        elif arr[mid] < s:
            left = mid + 1
        elif arr[mid] > s:
            right = mid - 1
    return res

# 简单测试
if __name__ == '__main__':
    strs = [None, "a", None, "a", None, "b", None, "c"]
    s = "a"
    print(index_of_None_strs(strs, s))  # 1

    strs = [None, "a", None, "a", None, "b", None, "c"]
    s = None
    print(index_of_None_strs(strs, s))  # -1

    strs = [None, "a", None, "a", None, "b", None, "c"]
    s = "d"
    print(index_of_None_strs(strs, s))  # -1

嗯,一气呵成!


有任何疑问和建议,欢迎在评论区留言和指正!

感谢您所花费的时间与精力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值