博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Alg]旋转有序数组的中二分查找
阅读量:2055 次
发布时间:2019-04-28

本文共 1496 字,大约阅读时间需要 4 分钟。

 

给定一个没有重复元素的旋转数组(它对应的原数组是有序的),求给定元素在旋转数组内的下标(不存在的返回-1),时间复杂度为logN。

如[4,5,6,7,0,1,2]就是一个旋转数组:

  • 查找3,返回-1;
  • 查找0,返回4;

根据中位数与旋转点相对位置查找

从中位数与旋转点的相对位置看,可以有:

  • 旋转点在中位数右侧:中位数及其左侧元素全部为升序,且小于中位数;
  • 旋转点与中位数相同或在中位数左侧:中位数及其右侧元素全部升序,且大于中位数;
def searchInShiftArray(ary:list, ele:int)->int:    def bisearch(ary, start, end):        if start>end:            return -1        mid = (start+end)//2        if ary[mid] == ele:            return mid        if ary[mid]>ele:            return bisearch(ary, start, mid-1)        else:             return bisearch(ary, mid+1, end)    def search(ary, start, end):        if start>end:            return -1        mid = (start+end)//2        if ary[mid] == ele:            return mid        if ary[mid]
ary[mid]: # mid在旋转点后,                if ary[end]>=ele:                    return bisearch(ary, mid+1, end)                return search(ary, start, mid-1)            # mid在旋转点前            return search(ary, mid+1, end)        else: # ary[mid]>ele            if ary[start]>ary[mid]: # mid在旋转点后,                return search(ary, start, mid-1)            # mid在旋转点前            if ary[start]<=ele:                return bisearch(ary, start, mid-1)            return search(ary, mid+1, end)    return search(ary, 0, len(ary)-1) 

切分数组查找

查找有序数组最方便的方式是二分查找,而旋转数组也可以看作是由‘旋转点’(数组中最小元素)切分的两个有序数组。可先找到旋转点,然后分别在两个有序数组中查找即可。

查找旋转点:

def findPivotPoint(ary:list)->tuple:    if ary[0]
ary[end]:            return findPoint(ary, mid+1, end)        else: #            if ary[mid]

转载地址:http://zgnlf.baihongyu.com/

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-15》437.路径总和III
查看>>
Leetcode C++《热题 Hot 100-16》448.找到所有数组中消失的数字
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-30》31.下一个排列
查看>>
Leetcode C++《热题 Hot 100-40》64.最小路径和
查看>>
Leetcode C++《热题 Hot 100-41》75.颜色分类
查看>>
Leetcode C++《热题 Hot 100-42》78.子集
查看>>
Leetcode C++《热题 Hot 100-43》94.二叉树的中序遍历
查看>>
Leetcode C++ 《第175场周赛-1 》5332.检查整数及其两倍数是否存在
查看>>
Leetcode C++ 《第175场周赛-2 》5333.制造字母异位词的最小步骤数
查看>>