leetcode 97: Search in Rotated Sorted Array

Search in Rotated Sorted ArrayMar 3 '12

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.

 

 

public class Solution {
    public int search(int[] A, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        // 8,9,10, 1,2,3,4,5,6,7   target 9
        int low=0, high=A.length-1;
        int mid = low + (high-low)/2;
        
        while(low<=high) {
            mid = low + (high-low)/2;
            
            if(A[mid]==target) return mid;
            else if(A[mid] > target) {
                if(A[mid] <= A[high]){ // high end is sorted.
                    high = mid-1;
                } else {
                    if(A[low] > target) {
                        low = mid + 1;
                    } else {
                        high = mid - 1;
                    }
                }
            } else {
                if(A[low]<=A[mid] ) {  // low end is sorted
                    low = mid + 1;
                } else {
                    if( A[high] < target) {
                        high = mid-1;
                    } else {
                        low = mid+1;
                    }
                }
            }
        }
        
        return -1; 
    }
}


 

first try wrong result. will miss in certain situation.

public class Solution {
    public int search(int[] A, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        // 8,9,10, 1,2,3,4,5,6,7   target 9
        int low=0, high=A.length-1;
        int mid = low + (high-low)/2;
        while(low<=high) {
            mid = low + (high-low)/2;
            
            if(A[mid]==target) return mid;
            else if(A[mid] > target) {
                if(A[low]<= target) {
                    high = mid-1;
                } else {
                    low = mid + 1;
                }
            } else {
                if(A[high] >= target) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
        }
        return -1; 
    }
}


 

 

posted @ 2013-03-04 09:25  西施豆腐渣  阅读(113)  评论(0编辑  收藏  举报