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
  • 相关阅读:
    html基础知识点
    uni-app之tabBar的自己配置
    uni-app之导航配置pages.json
    js获取链接?后边的参数名称或者值
    验证码输入自动聚焦下一个input或者删除自动聚焦上一个input
    VUE中/deep/深度作用域
    vue环境下新建项目
    vue中展示数据
    VUE环境项目搭建以及简单的运行例子
    ios设置音乐audio自动播放
  • 原文地址:https://www.cnblogs.com/asrman/p/4044704.html
Copyright © 2011-2022 走看看