zoukankan      html  css  js  c++  java
  • [leetcode] Search in Rotated Sorted Array @ Python [Figure][自配插图说明]

    Suppose a sorted array 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.

    There two solutions:

    Solution 1: How to hand the specific case involved point a,b and c?

    Solution 2: How to hand the specific case involved point a, nd d?

    Solution 1:

    class Solution:
        # @param A, a list of integers
        # @param target, an integer to be searched
        # @return an integer
        def search(self, A, target):
            return self.helper(A, target, 0, len(A)-1)
            
        def helper(self, A, target, low, high):
            if low > high: return -1
            mid = (low + high) / 2
            if target == A[mid]: return mid
            elif A[low] <= target < A[mid] or ( A[mid] <= A[high] and (target < A[mid] or target > A[high]) ):
                return self.helper(A, target,low, mid-1)
            else:
                return self.helper(A, target,mid+1, high)

    Solution 2:

    class Solution:
        # @param A, a list of integers
        # @param target, an integer to be searched
        # @return an integer
        def search(self, A, target):
            low,high = 0,len(A)-1
            while low <= high:
                mid = (low+high+1)/2
                if A[mid]==target: return mid
                if A[low] <= A[mid]:
                    if A[low] <= target < A[mid]: high=mid-1
                    else: low=mid+1
                else:
                    if A[mid] < target <= A[high]: low=mid+1
                    else: high=mid-1
            return -1
  • 相关阅读:
    mac 使用brew 安装php-redis
    thinkphp6 使用redis 实现消息队列
    Redis 桌面管理器:Another Redis Desktop Manager
    linux 查看并关闭shell脚本执行
    MySQL教程之concat以及group_concat的用法
    PHP redis 使用
    thinkphp6 command(自定义指令)
    git 使用
    linux shell中 "2>&1"含义
    linux crontab 定时任务
  • 原文地址:https://www.cnblogs.com/asrman/p/4044704.html
Copyright © 2011-2022 走看看