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

Leetcode:Search in Rotated Sorted Array

时间:2014-05-06 19:03:11      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二分查找   

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.

思路:先遍历一遍数组,找出分割点,将数组分成low1~high1,low2~high2两个有序子数组,其中A[high2]<A[low1]。

如果A[low1]<=target,则在low1~high1区间二分查找;

如果A[low1]>target,则在low2~high2区间二分查找。

时间复杂度为O(logn + n)。

代码如下:

class Solution {
public:
    int binSearch(int A[],int begin,int end,int target)
    {
        while(begin <= end)
        {
            int mid = begin + (end - begin) >> 1;
            if(A[mid] > target)
                end = mid - 1;
            else
                if(A[mid] < target)
                    begin = mid + 1;
                    else
                        return mid;
        }
        return -1;
    }
    int search(int A[], int n, int target) {
        if(n == 0)return -1;
        int i = 0;
        while(i < n - 1 && A[i] < A[i + 1])
            i++;
        if(i == n - 1)
        return binSearch(A,0,n - 1,target);
        if(i < n - 1)
        {
            int low1 = 0;
            int high1 = i;
            int low2 = i + 1;
            int high2 = n - 1;
            if(A[low1] <= target)
            {
                int idx = binSearch(A,low1,high1,target);
                if(idx >= 0)return idx;
                else return -1;
            }
            else
            {
                int idx = binSearch(A,low2,high2,target);
                if(idx >= 0)return idx;
                else return -1;
            }
        }
    }
};


Leetcode:Search in Rotated Sorted Array,布布扣,bubuko.com

Leetcode:Search in Rotated Sorted Array

标签:leetcode   二分查找   

原文地址:http://blog.csdn.net/u012118523/article/details/25006743

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