Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

LeetCode: Search in Rotated Sorted Array   解题报告

SOLUTION 1:

使用九章算法经典递归模板:

while (l < r - 1) 可以避免mid与left重合的现象。

其实和一般的二分法搜索没有太多区别。

问题是我们每次要找出正常排序的部分,你只需要比较mid, left,如果它们是正序,就代表左边是

正常排序,而右边存在断开的情况,也就是因为Rotated发生不正常序列。

例如:

4567012 如果我们取mid为7,则左边是正常序列,而右边7012不正常。

然后 我们再将target与正常排序的这边进行比较,如果target在左边,就丢弃右边,反之,丢弃

左边。一次我们可以扔掉一半。和二分搜索一样快。

 1 public class Solution {
 2     public int search(int[] A, int target) {
 3         if (A == null || A.length == 0) {
 4             return -1;
 5         }
 6         
 7         int l = 0;
 8         int r = A.length - 1;
 9         
10         while (l < r - 1) {
11             int mid = l + (r - l) / 2;
12             
13             if (A[mid] == target) {
14                 return mid;
15             }
16             
17             // left side is sorted.
18             // BUG 1: if don't use >= , and use L < r in while loop, than there is some problem.
19             if (A[mid] > A[l]) {
20                 if (target > A[mid] || target < A[l]) {
21                     // move to right;
22                     l = mid + 1;
23                 } else {
24                     r = mid - 1;
25                 }
26             } else {
27                 if (target < A[mid] || target > A[r]) {
28                     // move to left;
29                     r = mid - 1;
30                 } else {
31                     l = mid + 1;
32                 }
33             }
34         }
35         
36         if (A[l] == target) {
37             return l;
38         } else if (A[r] == target) {
39             return r;
40         }
41         
42         return -1;
43     }
44 }
View Code

相关文章:

  • 2021-06-16
  • 2021-12-13
  • 2021-09-10
  • 2021-12-16
  • 2021-11-03
  • 2021-10-14
  • 2022-12-23
猜你喜欢
  • 2021-05-22
  • 2022-12-23
  • 2021-12-30
  • 2021-12-24
  • 2021-11-04
  • 2021-10-26
相关资源
相似解决方案