leedcode解析—Python3—Search in Rotated Sorted Array—Medium

题目:
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.
You must write an algorithm with O(log n) runtime complexity.

我的思路:
一个find可以解决的问题,核心思想在于时间复杂度为O(log n) ,对于查找类的问题,时间复杂度为O(log n)一般为二分法。我的代码运行时间还可以,但是有点啰嗦有点长,时间关系暂时不优化.
Runtime: 32 ms(beats 97.3%)
Memory Usage: 14.4 MB(beats 98.7%)

我的解答:

class Solution:
    def search(self, nums, target):
        ind = 0
                       
        if nums[-1] < target < nums[0]:
            return -1
        elif target >= nums[0]:
            while target >= nums[0]:
                if target == nums[0]:
                    return ind
                if len(nums) == 1:
                    return -1
                if target >= nums[len(nums)//2] and nums[len(nums)//2] > nums[0]:
                    ind += len(nums)//2
                    nums = nums[len(nums)//2:]
                else:
                    nums = nums[:len(nums)//2]
        else:            
            while True: 
                while target < nums[0]:
                    if target == nums[0]:
                        return ind
                    if len(nums) == 1:
                        return -1
            
                    if nums[len(nums)//2] > nums[0]:
                       ind += len(nums)//2
                       nums = nums[len(nums)//2:]
                    else:
                        break
                if target == nums[0]:
                    return ind
                if len(nums) == 1:
                    return -1
                if target >= nums[len(nums)//2]:
                    ind += len(nums)//2
                    nums = nums[len(nums)//2:]
                else:
                    nums = nums[:len(nums)//2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值