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

阅读 22

2022-02-08

题目链接: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)

0 0 举报