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

LeetCode: Search in Rotated Sorted Array [032]

时间:2014-05-22 10:43:12      阅读:310      评论: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.


【题意】

给定一个有序的反转过的数组。这个数组的第一个值比最后一个值要大。
所给数组中没有重复元素。


【思路】

第一个值和最后一个值是反转的边界。
二分查找,根据第一个值和最后一个值确定target是在哪个区域


【代码】

class Solution {
public:
    int search(int A[], int n, int target) {
        if(n==0)return -1;
        if(A[0]<A[n-1]){
            //数组未发生反转,正常的二分查找
            int low=0, high=n-1;
            while(low<=high){
                int mid=(low+high)/2;
                if(A[mid]==target)return mid;
                else if(target<A[mid])high=mid-1;
                else low=mid+1;
            }
        }
        else{
            //数组未发生反转
            int low=0, high=n-1;
            while(low<=high){
                int mid=(low+high)/2;
                if(A[mid]==target)return mid;
                else if(target>A[mid]){
                    //先判断的位置,在确定target的位置
                    if(A[mid]>=A[0])low=mid+1;
                    else if(A[mid]<=A[n-1]){
                        if(target<=A[n-1])low=mid+1;
                        else if(target>=A[0])high=mid-1;
                        else break;
                    }
                    else break;
                }
                else{
                    //先判断的位置,在确定target的位置
                    if(A[mid]<=A[n-1])high=mid-1;
                    else if(A[mid]>=A[0]){
                        if(target>=A[0])high=mid-1;
                        else if(target<=A[n-1])low=mid+1;
                        else break;
                    }
                    else break;
                }
            }
        }
        return -1;
    }
};


LeetCode: Search in Rotated Sorted Array [032],布布扣,bubuko.com

LeetCode: Search in Rotated Sorted Array [032]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/26222199

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