Cover image for Interview Classic 150 Questions P33 Search in Rotated Sorted Array

Interview Classic 150 Questions P33 Search in Rotated Sorted Array


Timeline

timeline

2025-12-04

init

divide and conquer

Title:

The essence of binary search is to exclude the other half:

  • Ifleft halfis increasing and target is not in this interval, then target must be in theright half
  • Ifright halfis increasing and target is not in this interval, then target must be inleft half
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <vector>
using std::vector;

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

if (nums[mid] == target) {
return mid;
}

if (nums[left] <= nums[mid]) {
if (nums[left] <= target &&
target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}else if (nums[right] >= nums[mid]) {
if (nums[mid] < target &&
target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
};

leetcode hot 100 rewrite

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <vector>
using std::vector;

class Solution {
public:
int search(vector<int> &nums, int target)
{
// 1 <= nums.length <= 5000
// -104 <= nums[i] <= 104
// each value in nums is unique
// the problem data guarantees that nums was rotated at some unknown index
// -104 <= target <= 104

int n = nums.size();

int left = 0, right = n - 1, mid;

while (left <= right) {
mid = left + (right - left) / 2;

if (target == nums[mid])
return mid;

if (nums[mid] < nums[right]) {

if (target > nums[mid] && target <= nums[right]) // to the left of the increasing segment
left = mid + 1;
else
right = mid - 1;

} else { // in the reversed segment
if (target < nums[mid] && target >= nums[left]) // to the left of the reversed segment
right = mid - 1;
else
left = mid + 1;
}
}

return -1;
}
};