Find the array elements

topic

Given a sorted array, A, with possibly duplicated elements, find the indices of the first and last occurrences of a target element, x. Return -1 if the target is not found.

Example:
Input: A = [1,3,3,5,7,8,9,9,9,15], target = 9
Output: [6,8]

Input: A = [100, 150, 150, 153], target = 150
Output: [1,2]

Input: A = [1,2,3,4,5,6,10], target = 9
Output: [-1, -1]

analysis

Because the array is sorted, it is relatively simple. From left to right traverse once. 2 the cursor variable with l, r were recorded for the first time and the target position of the last element to occur. At the same time determine if the current element is greater than the target on early returns, reducing the number of searches.

Time complexity of O (n).

Code

class Solution: 
    def getRange(self, arr, target):
        l, r = -1, -1
        for i in range(len(arr)):
            if arr[i] > target:
                break
            elif arr[i] == target:
                if l == -1:
                    l = i
                r = i
        return [l, r]
  
# Test program 
arr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8] 
x = 2
print(Solution().getRange(arr, x))
# [1, 4]

Guess you like

Origin www.cnblogs.com/new-start/p/11639162.html