数据结构算法操作试题(C++/Python)——搜索旋转排序数组

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——搜索旋转排序数组,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/

2. 解答

python: 24ms, 11mb

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if not nums:return -1
        left = 0 
        right = len(nums)-1
        while left<=right:
            mid = (left+right)/2
            if nums[mid]==target:
                return mid
            if nums[left] <=nums[mid]:
                if nums[left]<=target<=nums[mid]:
                    right = mid-1
                else:
                    left = mid+1
            else:
                if nums[mid]<=target<=nums[right]:
                    left = mid+1
                else:
                    right = mid-1
        return -1

其他方法看 leetcode 链接 评论区~