1. 程式人生 > 其它 >刷題-力扣-面試題 10.05. 稀疏陣列搜尋

刷題-力扣-面試題 10.05. 稀疏陣列搜尋

題目連結

來源:力扣(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. 根據題目描述,在有序稀疏陣列中1查詢指定值
  2. 二分查詢,當二分的中間結點是稀疏值時,定位中間結點到左側相鄰第一個結點

程式碼

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;
    }
};