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

LintCode: Search in Rotated Sorted Array

时间:2016-03-13 06:08:47      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

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 {
    /** 
     *@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
        // handle corner case
        if (A == null || A.length == 0) {
            return -1;
        }
        
        // find the break point
        int start = 0, end = A.length - 1;
        int element = A[end];
        int point = 0;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int current = A[mid];
            if (current < element) {
                end = mid;
            } else {
                start = mid;
            }
        }
        if (A[start] < element) {
            point = start;
        } else {
            point = end;
        }
        
        if (A[point] == target) {
            return point;
        }
        end = A.length - 1;
        // decide which part to search
        if (target <= A[end]) {
            start = point + 1;
        } else {
            start = 0;
            end = point - 1;
        }
        // begin binary search
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int current = A[mid];
            if (target > current) {
                start = mid;
            } else if (target < current){
                end = mid;
            } else {
                return mid;
            }
        }
        if (A[start] == target) {
            return start;
        }
        if (A[end] == target) {
            return end;
        }
        return -1;
    }
}

The trick here is to find the break point first, then to search the element, both use binary search

LintCode: Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/dingjunnan/p/5271043.html

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