• Leetcode 33. Search in Rotated Sorted Array


    Description: There is an integer array nums sorted in ascending order (with distinct values).

    Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

    Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

    Link: 33. Search in Rotated Sorted Array

    Examples:

    Example 1:
    Input: nums = [4,5,6,7,0,1,2], target = 0
    Output: 4
    
    Example 2:
    Input: nums = [4,5,6,7,0,1,2], target = 3
    Output: -1
    
    Example 3:
    Input: nums = [1], target = 0
    Output: -1

    思路: 与平常的二分查找不同,有序list被折成两半了。二分查找的目的是确定目标值所在的区间,逐步缩小区间的大小,从而确定index的位置。我们会局限在以往的模式中,去比较nums[mid]和target的关系,但是这次需要考虑这一段区间是否有序,按照题解的思路:

    (1)如果target==A[m],那么m就是我们要的结果,直接返回;
    (2)如果A[m]<A[r],那么说明从m到r一定是有序的(没有受到rotate的影响),那么我们只需要判断target是不是在m到r之间,如果是则把左边缘移到m+1,否则就target在另一半,即把右边缘移到m-1。
    (3)如果A[m]>=A[r],那么说明从l到m一定是有序的,同样只需要判断target是否在这个范围内,相应的移动边缘即可。

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

    日期: 2021-04-10 

  • 相关阅读:
    后台跨域(CORS)
    golang 处理TCP粘包问题
    使用axios 发送ajax 下载文件
    Golang:在Redigo的RedisPool上选择DB
    puppeteer添加代理
    mongodb 权限操作
    alpine下安装icu-dev
    golang 导出CSV文件中文乱码的问题
    shell笔记
    Convert rune to int
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14641750.html
Copyright © 2020-2023  润新知