C/C++教程

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

本文主要是介绍力扣-面试题10.05 稀疏数组搜索(C++)- 二分变形,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目链接: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;
    }
};
这篇关于力扣-面试题10.05 稀疏数组搜索(C++)- 二分变形的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!