您的位置:首页 > 其它

[LeetCode]33 Search in Rotated Sorted Array

2015-01-02 16:45 369 查看
https://oj.leetcode.com/problems/search-in-rotated-sorted-array/
http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array.html
public class Solution {
public int search(int[] A, int target) {
if (A == null || A.length == 0)
return -1;
return find(A, 0, A.length - 1, target);
}

private int find(int[] A, int low, int high, int t)
{
if (low > high)
return -1;

if (low == high)
{
if (A[low] == t) return low;
return -1;
}

int mid = (low + high) / 2;

if (A[mid] == t)
{
return mid;
}

if (A[low] < A[mid]) // Since all numbers are unique, A[low] != A[mid]
{
if (A[low] <= t && t < A[mid])
return find(A, low, mid - 1, t);
else
return find(A, mid + 1, high, t);
}
else // A[low] > A[mid]
{
if (A[mid] < t && t <= A[high])
return find(A, mid + 1, high, t);
else
return find(A, low, mid - 1, t);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode