leetcode——33——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.


class Solution {
public:
    int search(vector<int>& nums, int target) {
        // 初始问题
        int l = 0, r = nums.size() - 1;
        // 不断重复来缩小问题规模
        while (l < r) {
            // 取中点,分情况讨论
            int m = (l + r) / 2;
            // 情况0
            if (target == nums[m]) return m;
            // 情况1
            if (nums[l] < nums[r]) {
                if (target > nums[m]) l = m + 1;
                if (target < nums[m]) r = m - 1;
            }
            else {
                // 情况2.1
                if (nums[m] >= nums[l]) {
                    if (target > nums[m] || target < nums[l]) {
                        l = m + 1;
                    }
                    else {
                        r = m - 1;
                    }
                }
                // 情况2.2
                else {
                    if (target < nums[m] || target > nums[r]) {
                        r = m - 1;
                    }
                    else {
                        l = m + 1;
                    }
                }
            }
        }
        // 计算答案
        if (l == r && nums[l] == target) return l;
        return -1;
    }
};

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