Leetcode34. 搜索范围

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jaster_wisdom/article/details/80636038

题目大意:给定一个升序的整型数组和一个目标值,找到这个目标值在数组中的开始和结束的位置

题目分析:本题使用二分查找的思想,不断地取中间元素,比较它和目标值的大小。若中间元素的值比目标值小,则在后面的部分查找;若比目标值大,则在前面的部分查找。若相等,则在该中间元素前后试探是否还有和目标值相等的元素,最后返回这个区间。

代码展示:

class Solution(object):
    def searchRange(self, nums, target):
        left = 0
        right = len(nums)-1
        while(left<=right):
            mid = (left+right)/2
            if nums[mid]<target:
                left = mid+1
            elif nums[mid]>target:
                right = mid-1
            else:
                left_bound = mid
                right_bound = mid
                while(left_bound-1>=left and nums[left_bound-1]==target):
                    left_bound -= 1
                while(right_bound+1<=right and nums[right_bound+1]==target):
                    right_bound += 1
                return [left_bound,right_bound]
        return [-1,-1]



方法二:还是使用二分查找的思想,分别找到该数组中与target相等的最早的一个元素和最晚的一个元素。然后返回这个区间即可。关键是看nums[mid]==target划分到哪个区间,若将其划分到前半部分,这样的话,会找到最早的那个元素的下标;划分到后半部分,则会找到最晚的那个元素的下标。

class Solution(object):
    def searchRange(self, nums, target):
        left = self.searchFirstAppear(nums,target)
        right = self.searchEndAppear(nums,target)
        return [left,right]
        
    def searchFirstAppear(self,nums,target):
        index = -1
        left = 0
        right = len(nums)-1
        while(left<=right):
            mid = (left+right)/2
            if nums[mid]<target:
                left = mid+1
            else:
                right = mid-1
            if nums[mid] == target:
                index = mid
        return index
        
    def searchEndAppear(self,nums,target):
        index = -1
        left = 0
        right = len(nums)-1
        while(left<=right):
            mid = (left+right)/2
            if nums[mid]<=target:
                left = mid+1
            else:
                right = mid-1
            if nums[mid] == target:
                index = mid
        return index

展开阅读全文

没有更多推荐了,返回首页