美文网首页
搜索旋转有序数组

搜索旋转有序数组

作者: 第六象限 | 来源:发表于2018-05-04 11:37 被阅读0次

描述
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.

代码

package binarySearch;
// 时间复杂度 O(log n),空间复杂度 O(1)
public class SearchRotated { public static void main(String[] args) throws Exception {
    int[] A = {11,12,13,15,17,22,28,30,2,4,5,6,9};
    System.out.println(new SearchRotated().search(A, 17));
}

    public int search(int[] A, int target) {
        if(A==null || A.length==0)
            return -1;
        int l = 0;
        int r = A.length-1;
        while(l<=r)
        {
            int m = (l+r)/2;
            if(target == A[m])
                return m;
            if(A[m]<A[r])
            {
                if(target>A[m] && target<=A[r])
                    l = m+1;
                else
                    r = m-1;
            }
            else
            {
                if(target>=A[l] && target<A[m])
                    r = m-1;
                else
                    l = m+1;
            }
        }
        return (A[l] == target) ? l : -1;
    }

}

相关文章

  • 搜索旋转有序数组

    描述Suppose a sorted array is rotated at some pivot unknown...

  • 搜索旋转数组

    搜索旋转数组 1.想法: 如果是拍好序的数组,那么直接使用二分查找进行搜索,现在旋转了后,我们可知至少有两段是有序...

  • 2020-2-16 刷题记录

    0X00 leetcode 刷题 7 道 搜索旋转排序数组(33) 搜索旋转排序数组 II(81) 寻找旋转排序数...

  • leetcode 33 搜索旋转排序数组

    leetcode 33 搜索旋转排序数组 第一次题解 思路:将数组分为两份,左边的数组可能是有序的可能是无须的,通...

  • swift搜索面试实战题-搜索旋转有序数组

    一个有序数组可能在某个位置旋转了。给定一个目标值,查找并返回这个元素在数组中的位置,如果不存在,则返回-1。假设数...

  • 旋转有序数组

    旋转有序数组:ll = [15,16,19,20,25,1,3,4,5,7,10,14]使用二分查找,分三种情况处...

  • 旋转数组的最小值

    旋转数组的最小值 所谓旋转数组,即是递增有序数组旋转右移动若干位得到的数组,这里的右移和java里的>>>有点不同...

  • 解题报告 - 搜索旋转排序数组

    解题报告 - 搜索旋转排序数组 LeetCode 搜索旋转排序数组 @TOC[%E6%96%87%E7%AB...

  • 0033-搜索旋转排序数组

    搜索旋转排序数组 方案一 如果中间的数小于最右边的数,则右半段是有序的,若中间数大于最右边数,则左半段是有序的,我...

  • [Leetcode] 33. 搜索旋转排序数组

    33. 搜索旋转排序数组 来源: 33. 搜索旋转排序数组 1. 解题思路 二分法查找 2. 代码

网友评论

      本文标题:搜索旋转有序数组

      本文链接:https://www.haomeiwen.com/subject/zahdrftx.html