首页 > 代码库 > LeetCode: Search in Rotated Sorted Array 解题报告
LeetCode: Search in Rotated Sorted Array 解题报告
Search in Rotated Sorted Array
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.
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 }
SOLUTION 2:
注意,如果while 循环使用l <= r来卡,则mid有可能会靠到l这这来,所以当判断是否有序时,我们必须使用<=
总之,这份代码就不需要最后再判断l,r的值。
1 public int search(int[] A, int target) { 2 if (A == null || A.length == 0) { 3 return -1; 4 } 5 6 int l = 0; 7 int r = A.length - 1; 8 9 while (l <= r) {10 int mid = l + (r - l) / 2;11 12 if (A[mid] == target) {13 return mid;14 }15 16 // left side is sorted.17 // BUG 1: if don‘t use >= , and use L < r in while loop, than there is some problem.18 if (A[mid] >= A[l]) {19 if (target > A[mid] || target < A[l]) {20 // move to right;21 l = mid + 1;22 } else {23 r = mid - 1;24 }25 } else {26 if (target < A[mid] || target > A[r]) {27 // move to left;28 r = mid - 1;29 } else {30 l = mid + 1;31 }32 }33 }34 35 return -1;36 }
FOLLOWUP:
LeetCode 新题: Find Minimum in Rotated Sorted Array 解题 ...
LeetCode 新题: Find Minimum in Rotated Sorted Array II 解 ...
代码: GitHub代码链接
LeetCode: Search in Rotated Sorted Array 解题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。