[leetcode] 33. Search in Rotated Sorted Array 解题报告

题目链接:https://leetcode.com/problems/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.


思路:由于是旋转数组,要确定应该往左还是往右搜索比较麻烦,我的解决方式是两个二分,一个二分找到右数组的左端点,这样就确定了两个数组的分界,然后根据target是不是比数组最后一个值大来确定要搜索左还是右数组。

如果target比数组最后一个值大,则说明target只能在左数组里搜索。

如果target比数组最后一个值小,则说明target要在右数组里搜索。

我觉得这样分开比较容易理解,也不容易出错。

代码如下:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int len = nums.size(),left = 0, right = len -1; 
        if(len == 0) return -1;
        while(left < right)//首先找到右子数组的左端点
        {
            int mid = (left + right)/2;
            if(nums[mid] < nums[right])
                right = mid;
            else
                left = mid + 1;
        }
        int low = (target > nums[len-1])?0:right;//新搜索数组的端点
        int high = (target > nums[len-1])?(right-1):(len-1);
        while(low <= high)//然后判断搜索哪一个数组,是不是比较明了^@^
        {
            int mid = (low + high)/2;
            if(nums[mid] < target)
                low = mid + 1;
            else
                high = mid - 1;
        }
        return nums[low]==target?low:-1;
    }
};


而另外更为正统的做法是做一次二分,分析应该搜索左边还是右边。每次二分有三种情况:

1. nums[mid] = target,则可以返回mid

2. nums[mid] < nums[right],说明在[mid, right]区间是右边递增的区间,然后判断target是否在这个区间内

1)如果nums[mid] < target <= nums[right],说明target在右边区间里,则left = mid + 1;

2)否则在左边区间里,搜索左边区间,right = mid - 1;

3. nums[mid] >= nums[right],说明[elft, mid]区间是在左边的递增区间,然后判断target是否在这个左边区间里

1)如果nums[left] <= target < nums[mid],说明target在这个区间里,则使right = mid - 1;

2)否则说明target在[mid, right]的不规则区间里,搜索右边区间,则使left = mid + 1;

然后考虑边界条件:

如果数组长度为1,则left = right,mid = left=right,如果nums[mid] = target,则直接返回,否则会进入条件3,然后循环结束,返回-1;

代码如下:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int len = nums.size(),left = 0, right = len -1; 
        while(left <= right)//首先找到右子数组的左端点
        {
            int mid = (left + right)/2;
            if(nums[mid] == target) return mid;
            if(nums[mid] < nums[right])
            {
                if(target > nums[mid] && target <= nums[right])
                    left = mid + 1;
                else
                    right = mid -1;
            }
            else
            {
                if(target >= nums[left] && target < nums[mid])
                    right = mid -1;
                else
                    left = mid + 1;
            }
        }
        return -1;
    }
};

第二种方法参考:http://bangbingsyb.blogspot.com/2014/11/leetcode-search-in-rotated-sorted-array.html

























你可能感兴趣的:(LeetCode,算法,search,binary)