Find out the string

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/iov3Rain/article/details/90242918

Title Description

There is a row over the array of strings sequence, but there are inserted some empty string, design an algorithm to identify the location of a given string. Find a part of the complexity of the algorithm should log level.

Given an array of string str, while a given array size n and X need to find a string, the string return to the position (zero-position).

Test sample:

["a","b","","c","","d"],6,"c"

Returns: 3

 

 

Modified binary search, the mid reset generation method.

starting from the high to mid to low down position, the first string is not empty

 

 

class Finder {
public:
    int findString(vector<string> str, int n, string x) {
        // write code here1
        int low = 0;
        int high = str.size() - 1;
        while(low < high)
        {
            int mid;
            for(mid = high; mid >= low; --mid)
                if(str[mid] != "")
                    break;
            if(str[mid] < x)
            {
                low = mid + 1;
            }
            else if(str[mid] > x)
            {
                high = mid - 1;
            }
            else
            {
                return mid;
            }
        }
        return -1;
    }
};

 

Guess you like

Origin blog.csdn.net/iov3Rain/article/details/90242918