Search in Rotated Sorted Array

来源:互联网 发布:淘宝3ds电玩良心店 编辑:程序博客网 时间:2024/04/30 05:59

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.

唯一要注意的就是要用A[l] <= A[m],因为m的确定是可能和l相等的
    public int search(int[] A, int target) {        return helper(A, target, 0, A.length-1);    }        int helper(int[] A, int target, int l, int h) {        if (l > h) {            return -1;        }        int m = l + (h-l)/2;        if (target == A[m]) {            return m;        }        if (A[l] <= A[m]) { // pivot is in the right, 注意这里要用=号,因为l,m可能相等!            if (A[l] <= target && target < A[m]) {                return helper(A, target, l, m-1);            } else  {                return helper(A, target, m+1, h);            }        } else { // pivot is in the left            if (target > A[m] && target <= A[h]) {                return helper(A, target, m+1, h);            } else {                return helper(A, target, l, m-1);            }        }    }


0 0
原创粉丝点击