Leetcode 33. Search in Rotated Sorted Array

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 33. Search in Rotated Sorted Array_第1张图片
Search in Rotated Sorted Array

2. Solution

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

Reference

  1. https://leetcode.com/problems/search-in-rotated-sorted-array/description/

你可能感兴趣的:(Leetcode 33. Search in Rotated Sorted Array)