簡體   English   中英

在排序數組中查找目標范圍的時間復雜度 - 這個解決方案在最壞的情況下是 O(N) 嗎?

[英]Time complexity of finding range of target in sorted array - Is this solution O(N) in the worst case?

我正在解決 LeetCode 問題34. Find First and Last Position of Element in Sorted Array ,它說:

給定一個按非降序排序的整數數組nums ,找到給定target的開始和結束位置。

如果在數組中找不到target ,則返回[-1, -1]

您必須編寫一個具有O(log n)運行時復雜度的算法。

由於問題需要logn運行時,我實現了二進制搜索邏輯。 但我不確定,並且認為,在基本條件中使用額外的while循環,我實際上在最壞的情況下會達到O(n) 真的嗎?

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        left = 0
        right = len(nums) - 1
        pos = [-1,-1]
        
        while left <= right:
            middle = (left + right) // 2
            """
                This is pure binary search until we hit the target. Once
                we have hit the target, we expand towards left and right
                until we find the number equal to the target. 
            """
            if nums[middle] == target:
                rIndex = middle
                while rIndex + 1 < len(nums) and nums[rIndex + 1] == target:
                    rIndex += 1
                pos[1] = rIndex
                
                lIndex = middle
                while lIndex - 1 >= 0 and nums[lIndex - 1] == target:
                    lIndex -= 1
                pos[0] = lIndex
                break
                    
            elif target > nums[middle]:
                left = middle + 1
            else:
                right = middle - 1
                
        return pos

這是我認為的示例數組,如下所示:

input = [8,8,8,8,8,8,8] , target = 8

當基本條件nums[middle] == target命中時,我將需要迭代整個數組,這使其運行時復雜度為O(n) ,對吧?

有趣的是,這個解決方案比 95% 的提交都快!! 但我認為 LeetCode 有一些問題!!!

是的,你是對的,循環會降低最壞情況的時間復雜度。 您正確地確定了當輸入數組只有目標值的副本而沒有其他值時會發生什么。

解決方案是執行兩次二分搜索:一種更喜歡向左側移動,另一種更喜歡向目標值的右側移動。

如果測試用例沒有徹底測試這個 O(n) 的行為,這個 O(n) 的解決方案就不會是一個糟糕的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM