leetcode刷题之二分查找

python实现简单二分查找: 

def binary_search(stack, val):
    begin = 0
    end = len(stack)
    while 1:
        mid = int(( begin + end ) / 2)
        if stack[mid] == val:
            return mid
        elif stack[mid] < val:
            if mid == len(stack)-1:
                return mid
            if val < stack[mid+1]:
                return mid + 1
            begin = mid + 1
        elif stack[mid] > val:
            if mid == 0:
                return 0
            if val > stack[mid-1]:
                 return mid 
            end = mid - 1

34. Find First and Last Position of Element in Sorted Array

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]

python 解法一:

单次循环遍历得到重复target的第一个iindex和后一个index.

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if target not in nums:
            return [-1, -1]
        lists = []
        for i in range(len(nums)):
            if nums[i] == target:
                lists.append(i)
            
        return [lists[0], lists[-1]]

python 解法二:

采用二分查找,时间复杂度降为O(logn)


        if target not in nums:
            return [-1, -1]
        begin = 0
        end = len(nums)-1
        while True:
            mid_index = int((begin + end) / 2)
            if nums[mid_index] == target:
                first = mid_index
                end = mid_index
                while nums[first] == target:
                    first -= 1
                    if first < 0:
                        break
                first += 1
                while nums[end] == target:
                    end += 1
                    if end > len(nums) - 1:
                        break
                end -= 1
                return [first, end]
            elif nums[mid_index] < target:
                begin = mid_index + 1
            elif nums[mid_index] > target:
                end = mid_index - 1
        
                
                
            
        

猜你喜欢

转载自blog.csdn.net/m0_37327467/article/details/88371580