面试题 10.05. 稀疏数组搜索
稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。
示例1:
输入: words = [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”,“dad”, “”, “”], s = “ta”
输出:-1
说明: 不存在返回-1。
示例2:
输入:words = [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”,“dad”, “”, “”], s = “ball”
输出:4
提示:
words的长度在[1, 1000000]之间
#define MAXN (int(1e6+7))
struct Node {
int id;
string* s;
} a[MAXN];
int n;
class Solution {
public:
int findString(vector<string>& words, string key) {
n = 0;
for(int i=0; i<words.size(); i++) {
if(words[i].empty()) continue ;
a[++n].id = i;
a[n].s = &words[i];
}
int lef = 1, rig = n, ret = -1;
while(lef <= rig) {
int mid = (lef + rig) >> 1;
string& now = *a[mid].s;
if(now == key) return a[mid].id;
if(now >= key) rig = mid - 1;
else lef = mid + 1;
}
return -1;
}
};