因为数组已排序,所以要利用折半查找法. cracking上的解法.
这是是数组里有重复的解法, 同样也适用于没有重复的数组.
public class Solution { /** * careercup 11.3 **/ // Would this affect the run-time complexity? How and why? // If too many duplicated items int the array, the run time complexity will turn from O(logn) to O(n) // Because, we have to search both sides, instead of searching ether side. public boolean search(int[] A, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return (searchR(A, 0, A.length-1, target) == -1) ? false : true; } private int searchR(int[] A, int left, int right, int x){ int mid = (left+right)/2; if(x == A[mid]) return mid; // found! if(left > right) return -1; // no target // 比较A[left]和A[mid]的大小,找到正常排序的一边. // 利用正常排序的那边, 判断x是在正常排序边,还是另一边. 若判断不出来,则两边都看. if(A[left] < A[mid]){ // 左边是正常排序的 if(x >= A[left] && x < A[mid]){ return searchR(A, left, mid-1, x); // x in left side, search left }else{ return searchR(A, mid+1, right, x); // x not in left side, search right } }else if(A[left] > A[mid]){ // 右边正常排序 if(x > A[mid] && x <= A[right]){ return searchR(A, mid+1, right, x); // x in right side, search right }else{ return searchR(A, left, mid-1, x); // x not in right side, search left } }else if(A[left] == A[mid]){ // 左边非正常排序, if(A[mid] != A[right]){ // 因为, A[mid] 和A[right]不相等, 所以右边正常排序 return searchR(A, mid+1, right, x); }else{ // 无法判断,两边都找 int result = searchR(A, left, mid-1, x); if(result == -1) result = searchR(A, mid+1, right, x); return result; } } return -1; } }