[leetcode 33]Search in Rotated Sorted Array

1 题目

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.

Hide Tags
 Array Binary Search
 
2 思路
想了半天,考虑的是target与medium和两个边的大小来决定下一步二分搜索的low与high的确定。
结果分支太多,有些问题没考虑到,放弃。
 
看别人的思路,
 
mid两边肯定有一边是排好序的,根据这个思路,就好做了。
3 代码
    //mid 的左边或右边总是有一边是排好序的。
    //若在排好序的里面,则简单搜索,否则就不在该排好序的这边
    public int search(int[] A, int target) {
        int low = 0;
        int high = A.length-1;
        
        while (low < high) {
            int mid = (low + high + 1)/2;
            if (A[mid] == target) return mid;
            if (A[mid] > A[low]) {
                if (target < A[low] || target > A[mid]) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            } else {
               if (target < A[mid] || target > A[high]) {
                   high = mid - 1;
               } else {
                   low = mid+1;
               }
            }
        }
        return low < A.length && A[low] == target ? low : -1;
    }
原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4460809.html