其他分享
首页 > 其他分享> > [LeetCode 解题报告]033. Search in Rotated Sorted Array

[LeetCode 解题报告]033. Search in Rotated Sorted Array

作者:互联网

Suppose an array sorted in ascending order 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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

考察:二分查找,首先我们数组nums=[0,1,2,4,5,6,7]的所有旋转情况,如下:

可以发现,无论怎样的旋转,要么前半段有序,要么后半段有序;那么怎么判断是前半段有序还是后半段有序呢。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if (nums.size() < 1 || (nums.size() == 1 && nums[0] != target))
            return -1;
        int left = 0, right = nums.size()-1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < nums[right]) { //后半段有序
                if (nums[mid] < target && nums[right] >= target)
                    left = mid + 1;
                else
                    right = mid - 1;
            }
            else { // 前半段有序
                if (nums[left] <= target && target < nums[mid])
                    right = mid - 1;
                else
                    left = mid + 1;
            }
        }
        return -1;
    }
};

完, 

标签:Search,target,nums,Rotated,mid,前半段,有序,Sorted,left
来源: https://blog.csdn.net/caicaiatnbu/article/details/102772077