【LeetCode 33】 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

思路

每次,左右區間一定有一個單調區間,根據區間兩端元素大小判斷target是否在單調區間。

代碼

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int l = 0, r = n-1;

        while (l <= r) {
            int mid = l + (r-l)/2;
            if (nums[mid] == target) return mid;
            if (nums[l] < nums[r]) {
                if (target > nums[mid]) l = mid + 1;
                else r = mid - 1;
            }
            else if (nums[mid] > nums[r]) {
                if (target >= nums[l] && target < nums[mid]) r = mid - 1;
                else l = mid + 1;
            }else {
                if (target >= nums[mid] && target <= nums[r]) l = mid + 1;
                else r = mid - 1;
            }
        }
        
        return -1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章