搜索旋转排序数组

假设按照升序排序的数组在预先未知的某个点上进行了旋转。

( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。

你可以假设数组中不存在重复的元素。

你的算法时间复杂度必须是 O(log n) 级别。

示例 1:

输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:

输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array

解题思路:先判断是否是旋转数组,不是的话,直接用二分搜索去查找,是的话则记录下标,再进行二分搜索。

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        n = len(nums)
        if n == 0:
            return -1
        if n < 2:
            if nums[0] == target:
                return 0
            else:
                return -1
        index = 0
        for i in range(1, n):
            if nums[i] < nums[i - 1]:
                index = i
                break
        if index == 0:
            max_index = n - 1
            min_index = 0
            mid = (max_index + min_index) // 2
            while max_index >= min_index:
                if nums[mid] > target:
                    max_index = mid - 1
                    mid = (max_index + min_index) // 2
                elif nums[mid] < target:
                    min_index = mid + 1
                    mid =  (max_index + min_index) // 2
                else:
                    return mid

        if nums[0] > target:
            max_index = n - 1
            min_index = index
            mid = (max_index + min_index) // 2
            while max_index >= min_index:
                if nums[mid] > target:
                    max_index = mid - 1
                    mid = (max_index + min_index) // 2
                elif nums[mid] < target:
                    min_index = mid + 1
                    mid =  (max_index + min_index) // 2
                else:
                    return mid
        elif nums[0] < target:
            max_index = index - 1
            min_index = 0
            mid = (max_index + min_index) // 2
            while max_index >= min_index:
                if nums[mid] > target:
                    max_index = mid - 1
                    mid = (max_index + min_index) // 2
                elif nums[mid] < target:
                    min_index = mid + 1
                    mid =  (max_index + min_index) // 2
                else:
                    return mid
        else:
            return 0
        return -1
点赞

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像

Title - Artist
0:00