标签:leetcode
题意:在旋转的有序数组中搜索某个元素,无重复数据public int search(int[] A, int target) { return bsearch(A, target, 0, A.length - 1); } /** * 二分搜索,无重复元素,判断是否为rotated * @param A * @param target * @param l * @param r * @return */ public int bsearch(int[] A, int target, int l, int r) { if(l <= r){ int mid = r + (l - r) / 2; if(A[l] > A[r]){//无序的情况 if(target > A[l]){ if(A[l] > A[mid]) return bsearch(A, target, l + 1, mid); else { if(target >= A[mid])return bsearch(A, target, mid, r); else return bsearch(A, target, l + 1, mid -1 ); } }else if(target == A[l]) return l; else { if(A[l] > A[mid]){ if(target > A[mid]) return bsearch(A, target, mid + 1, r); else return bsearch(A, target, l + 1, mid); }else { return bsearch(A, target, mid + 1, r); } } }else {//有序的情况 if(target == A[mid]) return mid; if(target > A[mid]) return bsearch(A, target, mid+1, r); else return bsearch(A, target, l, mid - 1); } }else return -1; }
[LeetCode] Search in Rotated Sorted Array
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45110467