數組元素查找

題目

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]code

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

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

分析

由於是排好序的數組,比較簡單。從左到右遍歷一次便可。用2個遊標變量 l, r 分別記錄第一次和最後一次目標元素出現的位置。同時判斷若是當前元素大於目標就提前返回,減小搜索次數。it

時間複雜度 O(n).io

代碼

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]
相關文章
相關標籤/搜索