search_rotate_array

  • 2022-12-14
  • 浏览 (551)

search_rotate_array.cpp 源码

//
// Created by roseduan on 2022/2/9.
//

// 搜索旋转排序数组

#include "vector"
using namespace std;

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

你可能感兴趣的文章

find_min_rotated_array

first_bad_version

first_last_in_array

0  赞