二分法及变形题

本文介绍了一种在已排序且含有空字符串的数组中查找指定字符串的方法。通过实现一个特殊二分查找算法,该算法能有效处理数组中出现的空字符串情况,并返回目标字符串的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个已经排好序的字符串数组,空字符串散布在该数组中,编写一个函数寻找一个 给定字符串的位置。

public static int getIndex(String[] strs, String str){
    if (strs == null || strs.length == 0 || str == null) {
        return -1;
    }
    int start = -1;
    int end = strs.length;
    int i = 0;
    while(start + 1 < end){
        int mid = start + (end - start) / 2;  //此写法和防止相加越界
        if(strs[mid] != null){
            if (strs[mid].compareTo(str) < 0) {
                start = mid;
            }else{
                  end = mid;
                          }
        }else{
            i = mid; //用i记录当前mid位置,然后往左边找第一个不为null的字符
            while(strs[i] == null && --i >= start+1);
            if (i < start+1 || strs[i].compareTo(str) < 0) {
                start = mid;
            }else{
                                   end = i;
            }
         }
      }
          if (start+1 >= strs.length || !strs[start+1].equals(str)) {
                        return -1;
                 }
          return start+1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值