首页 > 编程语言 > 详细

数组元素查找

时间:2019-10-09 09:08:40      阅读:133      评论:0      收藏:0      [点我收藏+]

题目

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]

分析

因为是排好序的数组,比较简单。从左到右遍历一次即可。用2个游标变量 l, r 分别记录第一次和最后一次目标元素出现的位置。同时判断如果当前元素大于目标就提早返回,减少搜索次数。

时间复杂度 O(n).

代码

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]

数组元素查找

原文:https://www.cnblogs.com/new-start/p/11639162.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!