标签:leetcode algorithm binarysearch
【题目】
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.
【二分思路】分情况讨论,数组可能有以下三种情况:
然后,再看每一种情况中,target在左边还是在右边,其中第一种情况还可以直接判断target有可能不在数组范围内。
【Java代码】
public class Solution { public int search(int[] A, int target) { int len = A.length; if (len == 0) return -1; return binarySearch(A, 0, len-1, target); } public int binarySearch(int[] A, int left, int right, int target) { if (left > right) return -1; int mid = (left + right) / 2; if (A[left] == target) return left; if (A[mid] == target) return mid; if (A[right] == target) return right; //图示情况一 if (A[left] < A[right]) { if (target < A[left] || target > A[right]) { //target不在数组范围内 return -1; } else if (target < A[mid]) { //target在左边 return binarySearch(A, left+1, mid-1, target); } else { //target在右边 return binarySearch(A, mid+1, right-1, target); } } //图示情况二 else if (A[left] < A[mid]) { if (target > A[left] && target < A[mid]) { //target在左边 return binarySearch(A, left+1, mid-1, target); } else { //target在右边 return binarySearch(A, mid+1, right-1, target); } } //图示情况三 else { if (target > A[mid] && target < A[right]) { //target在右边 return binarySearch(A, mid+1, right-1, target); } else{ //target在左边 return binarySearch(A, left+1, mid-1, target); } } } }
public class Solution { public int search(int[] A, int target) { int len = A.length; if (len == 0) { return -1; } else if (len == 1) { return target==A[0] ? 0 : -1; } int left = 0, right = len-1; while (left < right) { int mid = left + (right-left)/2; if (target == A[mid]) { return mid; } else if (target == A[left]) { return left; } else if (target == A[right]) { return right; } //第一种情况中,target不在数组范围内 if (A[left]<A[right] && (target<A[left] || target>A[right])) { return -1; } //第一、二种情况的左边,即连续上升的左边,且target在这段内 if (A[left]<A[mid] && target>A[left] && target<A[mid]) { right = mid - 1; continue; } //第一、三种情况的右边,即连续上升的右边,且target在这段内 if (A[mid]<A[right] && target>A[mid] && target<A[right]) { left = mid + 1; continue; } //如果上面情况都不满足,那么可能在第二种情况的右边 if (A[mid] > A[right]) { left = mid + 1; continue; } //如果上面情况都不满足,第三种情况的左边 if (A[left] > A[mid]) { right = mid - 1; continue; } } return -1; } }
个人感觉还是自己那样写思路比较清晰。
【LeetCode】Search in Rotated Sorted Array 解题报告
标签:leetcode algorithm binarysearch
原文地址:http://blog.csdn.net/ljiabin/article/details/40453607