[LeetCode 33] 搜索旋转排序数组

33. 搜索旋转排序数组

基本思想就是改一下二分搜索

分两种情况:

  1. 最大值在mid右边,此时nums[mid] > nums[high](如图中红字)
    又分两种情况如图中绿字部分
 if (nums[low] <= target && target < nums[mid]) 
    high = mid - 1;
 else  
    low = mid + 1;
  1. 最大值在mid左边,此时nums[mid] <= nums[high](如图中红字)
    又分两种情况如图中绿字部分
if (nums[mid] < target && target <= nums[high]) 
    low = mid + 1;
else 
    high = mid - 1;
#include 
#include 
#include 
using namespace std;

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

int main() {
    Solution s;
    vector nums = {
        6, 7, 0, 1, 2, 3, 5,
    };
    for (int i = 0; i < nums.size(); i++) {
        cout << s.search(nums, nums[i]) << endl;
    }
    return 0;
}

你可能感兴趣的:([LeetCode 33] 搜索旋转排序数组)