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

Search in Rotated Sorted Array

时间:2015-03-08 11:44:14      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

  二分查找

我的代码:

技术分享
public class Solution {
    public int search(int[] A, int target) {
        if(A == null || A.length == 0)  return -1;
        int left = 0;
        int right = A.length - 1;
        int index = helperSearch(A, left, right, target);
        return index;
    }
    public int helperSearch(int[] A, int left, int right, int target)
    {
        if(left == right)
        {
            if(A[left] == target)   return left;
            else return -1;
        }
        if(left > right)    return -1;
        int mid = (left + right)/2;
        if(A[mid] == target)    return mid;
        if(A[left] < A[right])
        {
            if(A[mid] > target) return helperSearch(A, left, mid - 1, target);
            else    return  helperSearch(A, mid + 1, right, target);
        }
        else
        {
            return Math.max(helperSearch(A, left, mid - 1, target), helperSearch(A, mid + 1, right, target));
        }
    }
}
View Code

他人代码:

技术分享
public class Solution {
    public int search(int[] A, int target) {
        if(A == null || A.length == 0)  return -1;
        int left = 0;
        int right = A.length - 1;
        while(left <= right)
        {
            int mid = (left + right)/2;
            if(A[mid] == target)    return mid;
            if(A[left] <= A[mid])
            {
                if(A[left] > target || A[mid] < target) left = mid + 1;
                else    right = mid - 1;
            }
            else
            {
                if(A[right] < target || A[mid] > target) right = mid - 1;
                else left = mid + 1;
            }
        }
        return -1;
    }
}
View Code

学习之处:

  • 对于rotate array 二分一刀下去,总有一半是可以判断是否有序的。
  • left + 1 < right 后面会剩余一个或者两个数字需进一步判断 left <= right catch 到了所有的数据

Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4321426.html

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