问题分析

在旋转排序数组上应用二分查找,若数组中的元素都不相同,则可以按下图分析:

  • 若a[mid] > a[high], 则代表mid位于旋转数组的左半段;

  • 若a[mid] < a[low],则代表mid位于旋转数组的右半段

  • 否则,代表区间[low, high]是个递增数组,不存在旋转

若数组中可能存在重复元素,则需要按下图分析:

  • 若a[mid] < a[low], 则代表处于状态①
  • 若a[mid] > a[high], 则代表处于状态②
  • 若a[mid] = a[low] = a[high],则代表处于状态③或④
  • 否则,代表区间[low, high]不存在反转

1. 寻找旋转排序数组中的最小值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int findMin(int[] nums) {
int low = 0, high = nums.length-1;

while(low < high){
int mid = low + (high - low) / 2;
if(nums[mid] > nums[high]){
low = mid+1;
}
else if(nums[mid] < nums[low]){
high = mid;
}
else{
high = mid;
}
}

return nums[low];
}

2. 寻找旋转排序数组中的最小值II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public int findMin(int[] nums) {

int low = 0, high = nums.length-1;

while(low < high){
int mid = low + (high - low) / 2;
if(nums[mid] < nums[low]){
high = mid;
}
else if(nums[mid] > nums[high]){
low = mid + 1;
}
else if(nums[mid] == nums[low] && nums[mid] == nums[high]){
high--;
}
else{
high = mid;
}
}

return nums[low];


}

3. 搜索旋转排序数组

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
public int search(int[] nums, int target) {

int low = 0, high = nums.length-1;

while(low <= high){
int mid = low + (high - low) / 2;
if(nums[mid] == target){
return mid;
}

if(nums[mid] > nums[high]){
if(target >= nums[low] && target < nums[mid]){
high = mid - 1;
}
else{
low = mid + 1;
}
}
else if(nums[mid] < nums[low]){
if(target > nums[mid] && target <= nums[high]){
low = mid + 1;
}
else {
high = mid - 1;
}
}
else {
if(target > nums[mid]){
low = mid + 1;
}
else{
high = mid - 1;
}
}
}

return -1;
}

4. 搜索旋转排序数组II

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
42
43
public boolean search(int[] nums, int target) {

int low = 0, high = nums.length-1;

while(low <= high){
int mid = low + (high - low) / 2;
if(nums[mid] == target){
return true;
}

if(nums[mid] > nums[high]){
if(target >= nums[low] && target < nums[mid]){
high = mid - 1;
}
else{
low = mid + 1;
}
}
else if(nums[mid] < nums[low]){
if(target > nums[mid] && target <= nums[high]){
low = mid + 1;
}
else{
high = mid - 1;
}
}
else if(nums[mid] == nums[low] && nums[mid] == nums[high]){
low++;
high--;
}
else{
if(target > nums[mid]){
low = mid + 1;
}
else{
high = mid - 1;
}
}

}

return false;
}