码迷,mamicode.com
首页 > 其他好文 > 详细

Search in Rotated Sorted Array

时间:2017-05-04 09:49:34      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:==   strong   ant   ram   target   return   else   important   div   

O(logN)

Important Point:

Once the target is in one section, use the point in that section as benchmark

In this problem, if the target >= startVal, use A[mid] < startVal to throw the other section.

public class Solution {
    /** 
     *@param A : an integer rotated sorted array
     *@param target :  an integer to be searched
     *return : an integer
     */
    public int search(int[] A, int target) {
        // write your code here
        if (A == null || A.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = A.length - 1;
        int startVal = A[start];
        int endVal = A[end];
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] == target) {
                    return mid;
            }
            if (target >= startVal) {
               if (A[mid] < startVal || A[mid] > target) {
                    end = mid;
                } else {
                    start = mid;
                }
            } else {
                if (A[mid] > endVal || A[mid] < target) {
                    start = mid;
                } else {
                    end = mid;
                }
            }
        }
        
        if (A[start] == target) {
            return start;
        }
        if (A[end] == target) {
            return end;
        }
        return -1;
    }
}

 

Search in Rotated Sorted Array

标签:==   strong   ant   ram   target   return   else   important   div   

原文地址:http://www.cnblogs.com/codingEskimo/p/6805072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!