Sparse Search
EXAMPLE
Input: ball, {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}
Output: 4int binary_search(vector<string> &strs, int low, int high, string target) {
if (high < low) return -1;
int middle = low + ((high - low) / 2);
if (strs.at(middle).empty()) {
int left = middle - 1;
int right = middle + 1;
while (left > low && right < high) {
if (strs.at(left).empty())
left--;
else {
middle = left;
break;
}
if (strs.at(right).empty())
right++;
else {
middle = right;
break;
}
}
}
if (strs.at(middle) == target) return middle;
// search right
else if (strs.at(middle) < target) {
binary_search(strs, middle + 1, high, target);
}
else {
binary_search(strs, low, middle - 1, target);
}
}
int sparse_search(vector<string> &strs, string str) {
if (strs.empty() || str == "") return -1;
return binary_search(strs, 0, strs.size() - 1, str);
}
int main() {
vector<string> strings = { "at", "", "", "", "ball", "", "", "car", "", "", "dad", "", "" };
cout << sparse_search(strings, "ball") << endl;
}Last updated