[LeetCode solving report] 033. Search in Rotated Sorted Array

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/caicaiatnbu/article/details/102772077

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

Visit: binary search, we first of all rotating circumstances array nums = [0,1,2,4,5,6,7], as follows:

  • 0,1, 2,4,5,6,7
  • 1,2,4,5,6,7,0
  • 2,4,5,6,7,0,1
  • 4,5,6,7,0,1,2
  • 5,6,7,0,1,2,4
  • 6,7,0,1,2,4,5
  • 7,0,1,2,4,5,6

It can be found, no matter how the rotation, or the first half of an orderly, or the second half and orderly; so how is the judge ordered the first half or the second half ordered it.

  • nums [mid] <nums [right] After half an orderly
  • nums [left] <nums [mid] ordered first half
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;
    }
};

Finish, 

Guess you like

Origin blog.csdn.net/caicaiatnbu/article/details/102772077