0
点赞
收藏
分享

微信扫一扫

力扣-面试题10.05 稀疏数组搜索(C++)- 二分变形

Yaphets_巍 2022-02-08 阅读 22

题目链接:https://leetcode-cn.com/problems/sparse-array-search-lcci/
题目如下:
在这里插入图片描述

class Solution {
public:
    int findString(vector<string>& words, string s) {
        int low=0,high=words.size()-1;
        while(low<=high){
            int mid=low+(high-low)/2;

            if(words[mid]==s) return mid;
            else if(words[mid]==""){//因为字符串数组已经排好序,即从小到大,且参杂“”,此处为空
                if(words[low]==s) return low;
                else low++;
            }else if(words[mid]<s) low=mid+1;//非空,即能比较大小
            else high=mid-1;
        }

        return -1;
    }
};
举报

相关推荐

0 条评论