# [Leetcode]_33 Search in Rotated Sorted Array

/**
*  Index: 33
*  Title: Search in Rotated Sorted Array
*  Author: ltree98
**/

class Solution {
public:
int search(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++)    {
if(nums[i] == target)
return i;
}
return -1;
}
};

class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, h = nums.size()-1;
int m = (l+h)/2;

while(l <= h)   {
if(nums[m] > target)
h = m-1;
else if(nums[m] < target)
l = m+1;
else
return m;
m = (l+h)/2;
}

return -1;
}
};

#### 二分查找的变异

n[m] < target => n[h] < target => n[m] <= n[h] (target在左边) => h = m-1
n[m] > n[h] (target在右边) => l = m+1
n[h] > target (target在右边) => l = m+1
n[h] == target => 返回 h

n[m] > target => n[l] < target (target在左边) => h = m-1
n[l] > target => n[m] >= n[l] (target在右边) => l = m+1
n[m] < n[l] (target在左边) => h = m-1
n[l] == target => 返回 l

n[m] == target => 返回 m

class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, h = nums.size()-1;
int m = (l+h)/2;

while(l <= h)   {
if(nums[m] > target)    {
if(nums[l] < target)    h = m-1;
else if(nums[l] > target)
if(nums[m] >= nums[l])  l = m+1;
else    h = m-1;
else    return l;
}
else if(nums[m] < target)   {
if(nums[h] < target)
if(nums[m] <= nums[h])  h = m-1;
else    l = m+1;
else if(nums[h] > target) l = m+1;
else    return h;
}
else
return m;
m = (l+h)/2;
}

return -1;
}
};

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客