稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。
示例1:
输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
输出:-1
说明: 不存在返回-1。
示例2:
输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
输出:4
提示:
- words的长度在[1, 1000000]之间
分析:
方法1:朴素解法
最简单粗暴的方法就是直接遍历数组,一个一个比较,相等返回索引,遍历完返回 -1 即可。
时间复杂度:O(n*m) n 为数组长度,m 为给定字符串的长度,equals() 方法会逐个字符比较,每一个字符串都至少比较 m 次。
空间复杂度:O(1)
class Solution {
public int findString(String[] words, String s) {
//遍历
for(int i = 0; i < words.length; ++i){
//相等
if(words[i].equals(s)){
return i;
}
}
return -1;
}
}
方法2:二分查找
因为给定数组是排好序的,因此我们可以通过比较顺序来进行二分查找,若二分点比目标字符串大,那么就往左遍历,比目标字符串小就往右遍历。但是数组中存在空字符串的情况,这种时候只需要将右边界左移即可(前提是右边界不为目标字符串)。
时间复杂度:O(m * log n) n 为数组长度,m 为给定字符串的长度,equals() 和 compareTo() 方法会逐个字符比较,每一个字符串都至少比较 m 次。
空间复杂度:O(1)
class Solution {
public int findString(String[] words, String s) {
//定义双指针
int i = 0, j = words.length-1;
//遍历
while(i <= j){
//二分点
int mid = 1 + i + j >> 1;
//该位置为空,移动右边界
if(words[mid].isEmpty()){
//判断右边界是否为目标字符串
if(words[j].equals(s)){
return j;
}
//移动右边界
j--;
continue;
}
//两个字符串相比较
int compare = words[mid].compareTo(s);
//相等
if(compare == 0){
return mid;
}
//二分点小于字符串
if(compare > 0){
j = mid-1;
continue;
}
//大于字符串
i = mid+1;
}
return -1;
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sparse-array-search-lcci