首页 > 代码库 > Search in Rotated Sorted Array
Search in Rotated Sorted Array
O(logN)
Important Point:
Once the target is in one section, use the point in that section as benchmark
In this problem, if the target >= startVal, use A[mid] < startVal to throw the other section.
public class Solution { /** *@param A : an integer rotated sorted array *@param target : an integer to be searched *return : an integer */ public int search(int[] A, int target) { // write your code here if (A == null || A.length == 0) { return -1; } int start = 0; int end = A.length - 1; int startVal = A[start]; int endVal = A[end]; while (start + 1 < end) { int mid = start + (end - start) / 2; if (A[mid] == target) { return mid; } if (target >= startVal) { if (A[mid] < startVal || A[mid] > target) { end = mid; } else { start = mid; } } else { if (A[mid] > endVal || A[mid] < target) { start = mid; } else { end = mid; } } } if (A[start] == target) { return start; } if (A[end] == target) { return end; } return -1; } }
Search in Rotated Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。