(Medium #34) Find First and Last Position of Element in Sorted Array

Problem

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

My solution

class Solution:
    def searchRange(self, nums, target):
        def search(nums, target):
            s, e = 0, len(nums)-1
            
            if nums[s] > target or nums[e] < target:
                return -1

            while s <= e:
                m = int((s+e) / 2)
    
                if nums[m] == target:
                    return m
                elif nums[m] > target:
                    e = m-1                   
                else: ## nums[m] < target
                    s = m+1
            return -1
        
        s, e = 0, len(nums)-1
        if len(nums) == 0:
            return [-1, -1]
        if nums[s] > target:
            return [-1, -1]
        if nums[e] < target:
            return [-1, -1]
        
        m = search(nums,target)
        if m == -1:
            return [-1, -1]
        
        ms = m
        while len(nums[:ms]) > 0:
            if search(nums[:ms],target) == -1:
                break
            else:
                ms = search(nums[:ms],target)
        
        me = m
        while len(nums[me+1:]) > 0:
            if search(nums[me+1:],target) == -1:
                break
            else:
                me = search(nums[me+1:],target)+me+1
                
        return [ms, me]                       
Runtime: 104ms, Memory: 14.8MB

댓글