LintCode: 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 become4 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.
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 // handle corner case if (A == null || A.length == 0) { return -1; } // find the break point int start = 0, end = A.length - 1; int element = A[end]; int point = 0; while (start + 1 < end) { int mid = start + (end - start) / 2; int current = A[mid]; if (current < element) { end = mid; } else { start = mid; } } if (A[start] < element) { point = start; } else { point = end; } if (A[point] == target) { return point; } end = A.length - 1; // decide which part to search if (target <= A[end]) { start = point + 1; } else { start = 0; end = point - 1; } // begin binary search while (start + 1 < end) { int mid = start + (end - start) / 2; int current = A[mid]; if (target > current) { start = mid; } else if (target < current){ end = mid; } else { return mid; } } if (A[start] == target) { return start; } if (A[end] == target) { return end; } return -1; } }
The trick here is to find the break point first, then to search the element, both use binary search
posted on 2016-03-13 00:24 dingjunnan 阅读(128) 评论(0) 编辑 收藏 举报