题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sparse-array-search-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。
示例1:
输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
输出:-1
说明: 不存在返回-1。
示例2:
输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
输出:4
提示:
- words的长度在[1, 1000000]之间
题目分析
- 根据题目描述,在有序稀疏数组中1查找指定值
- 二分查找,当二分的中间结点是稀疏值时,定位中间结点到左侧相邻第一个结点
代码
class Solution {
public:
int findString(vector<string>& words, string s) {
int left = 0;
int right = words.size() - 1;
int mid = 0;
// 找到第一个有效的字符串位置
while (left <= right && words[left] == "") { ++left; }
// 找到最后一个有效的字符串位置
while (right >= left && words[right] == "") { --right; }
// 二分查找指定的字符串位置
while (left <= right) {
mid = left + (right - left) / 2;
while (mid >= left && words[mid] == "") { --mid; }
if (words[mid] == s) { return mid; }
else if (words[mid] > s) {
right = mid - 1;
while (right >= left && words[right] == "") { --right; }
}
else {
left = mid + 1;
while (left <= right && words[left] == "") { ++left; }
}
}
return -1;
}
};