面試題 10.05. 稀疏陣列搜尋(C++)
阿新 • • 發佈:2020-08-28
目錄
題目
稀疏陣列搜尋。有個排好序的字串陣列,其中散佈著一些空字串,編寫一種方法,找出給定字串的位置。
示例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 len = words.size();
if(len==0){
return -1;
}
for(int i=0;i<len;i++){
if(words[i]==s)
return i;
}
return -1;
}
};
二分查詢法
相對於普通二分查詢,還需要注意如下幾點:
- left 和right可能對應的是空字串,還需要人為的判斷並縮小邊界。
- 計算出的mid可能對應的也是空值。這裡的策略是將mid向右偏,直到不為空或者接觸到右邊界:如果到達右邊界,說明mid和right這一段全為空字串,沒有目標元素。所以將right更新為最初的mid即可。
具體程式碼如下:
class Solution {
public:
int findString(vector<string>& words, string s) {
int len = words.size();
if(len==0){
return -1;
}
int left=0,right=len-1;
while(left<=right){
//先排除左右邊界是空字串的情況
//因為按ASCII碼排序不包含空字串
if(words[left].size()==0){
left++;
continue;
}
if(words[right].size()==0){
right--;
continue;
}
int mid = (left + right)/2;
//排除mid也是空字串的情況
while(words[mid].size()==0){
mid++;
if(mid==right){
//說明mid到right之間沒有我們想要的答案
if(words[right]==s)
return right;
//將right更新為初始的mid
right = (left + right)/2;
continue;
}
}
//經過上層刪選的mid肯定不為空字串
if(words[mid]==s)
return mid;
else if(words[mid]>s)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
};