LintCode 62. Search in Rotated Sorted Array 原创Java参考解答

LintCode 62. Search in Rotated Sorted Array 原创Java参考解答

问题描述

http://www.lintcode.com/en/problem/search-in-rotated-sorted-array/

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.

Example

For [4, 5, 1, 2, 3] and target=1, return 2.

For [4, 5, 1, 2, 3] and target=0, return -1.

解题思路

题目是在一种已按大小排序但被旋转过的数组(Rotated Sorted Array,RST)中查找目标值target。

通过题目给出的例子,可以看到这种数组的特点是由小变大,到了某一个位置可能会突然下降,然后再次逐渐由小变大。值得注意的是数组如[1, 2, 3] 其实也算作Rotated Sorted Array,它假定只是把第一个元素和自己做位置调换。

这道题运用二分法解决。分两次二分法,第一次找到这个RST中的最小元素位置,从而通过比较target和最小元素大小关系,判断target可能是在的数组中左右哪段区间。接着,再一次二分法查找该区间是否有目标值。

参考代码

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) { 
        if (A == null || A.length == 0) { 
            return -1; 
        } 
         
        int minPosition = 0; 
        int start = 0; 
        int end = A.length - 1; 
        while (start + 1 < end) { 
            int mid = start + (end - start) / 2; 
            if (A[mid] > A[end]) { 
                start = mid; 
            } else { 
                end = mid; 
            } 
        }         
         
        if (A[start] < A[end]) { 
            minPosition = start; 
        } else { 
            minPosition = end; 
        } 
         
 
        if (A[minPosition] == target) { 
            return minPosition; 
        } else { 
            if (A[A.length - 1] < target) { 
                start = 0; 
                end = minPosition - 1; 
            } else { 
                start = minPosition; 
                end = A.length - 1; 
            } 
        } 
         
        while (start + 1 < end) { 
            int mid = start + (end - start) / 2; 
            if (A[mid] == target) { 
                return mid; 
            } else if (A[mid] < target) { 
                start = mid; 
            } else { 
                end = mid; 
            } 
        }          
         
        if (A[start] == target) { 
            return start; 
        } 
        if (A[end] == target) { 
            return end; 
        }         
        return -1; 
    } 
} 

相关题目

LintCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。