9.5 练手 腾讯50题 Search in Rotated Sorted Array

Leetcode 33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Your algorithm's runtime complexity must be in the order of O(log n).

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

要求时间复杂度是O(logn)因此确定 应该是在原数组上操作,可以用一个二分法的变式来写,代码如下:

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        n = len(nums)
        if n == 0:
            return -1
        if n == 1 :
            if nums[0] == target:
                return 0
            else:
                return -1
        pivot = n//2
        output = 0
        while n > 0:
            if nums[pivot] == target:
                output = output + pivot
                break
            elif nums[pivot] > target:
                if(nums[0] <= target and nums[0] < nums[pivot])\
                or (nums[0] >= target and nums[0] > nums[pivot]):
                    nums = nums[0:pivot]
                else:
                    nums = nums[pivot+1:]
                    output += pivot+1
            elif nums[pivot] < target:
                if(nums[-1] >= target and nums[-1] > nums[pivot])\
                or (nums[-1] <= target and nums[-1] < nums[pivot] ):
                    nums = nums[pivot+1:]
                    output += pivot+1
                else:
                    nums = nums[0:pivot]
            n = len(nums)
            pivot = n//2
        if len(nums) == 0:
            return -1
        else:
            return output

beat60+%

发现如果不用替换数组的方法直接改指针或者index速度会更快:

代码如下:

class Solution(object):
    def search(self, A, target):
        l,r = 0,len(A)-1
        while l <= r:
            m = (l+r)//2
            if A[m] == target:
                return m
            else:
                if A[m] < A[r]: 
                    if A[m] <= target <=A[r]:
                        l = m +1
                    else: 
                        r = m -1
                else:
                    if A[l]<= target <= A[m]:
                        r = m -1
                    else:
                        l = m + 1
        return -1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值