[LeetCode]033-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.

Solution:
其实遍历一遍也就O(n)。

(1)采用遍历和二分相结合
也Accept了。
思路就是从后往前,一边遍历一边找到“质变点”。然后将初始到这个点做一个二分查找。

int search(vector<int>& nums, int target) 
    {
        int n = nums.size();
        int i = 0;
        for(i = n-1;i>=1 && (nums[i] > nums[i-1]);i--)
        {
            if(target == nums[i])
                return i;
        }
        if(target == nums[i])
            return i;
        int j = 0;
        i --;
        return BinarySearch(nums,j,i,target);
    }
    int BinarySearch(vector<int>& nums,int begin,int end,int target)
    {
        if(begin <= end)
        {
            int mid = (begin + end )/ 2;
            if(target < nums[mid])
            {
                BinarySearch(nums,begin,mid-1,target);
            }
            else if(target > nums[mid])
            {
                BinarySearch(nums,mid+1,end,target);
            }
            else
                return mid;
        }
        else
            return -1;
    }

(2)纯二分查找。
算是二分查找的改进版本,网上关于这个的介绍很多。确实够快。

    int search(vector<int>& nums, int target) 
    {
        if(nums.size() == 1)
            return target == nums[0]?0:-1;
        int left = 0;
        int right = nums.size()-1;
        int mid = 0;
        while(left <= right)
        {
            mid = (left+right)/2;
            if(nums[mid] == target)
            {
                return mid;
            }
            if(nums[left] <= nums[right])//最左边小于最右边,说明按序排好了
            {
                if(target < nums[mid])
                    right = mid - 1;
                else
                    left = mid +1;
            }
            else if(nums[left] <= nums[mid])
            {
                if(target > nums[mid] || target<nums[left])
                    left = mid +1;
                else
                    right = mid -1;
            }
            else
            {
                if(target < nums[mid] || target > nums[right])
                    right = mid-1;
                else
                    left = mid +1;
            }
        }
        return -1;
    }

介绍这个方法,看懂一张图就行了。
在这篇文章里:
http://blog.csdn.net/ljiabin/article/details/40453607

你可能感兴趣的:(LeetCode)