您的位置:首页 > 其它

leetcode - 33.Search in Rotated Sorted Array

2017-03-02 19:56 621 查看

Search in Rotated Sorted Array

Suppose an array sorted in ascending order 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.

Solution1:

public int search(int[] nums, int target) {
int length = nums.length;
if (length == 0) {
return -1;
}
if (length == 1) {
return nums[0] == target ? 0 : -1;
}

int index = 0;
while (index < length - 1 && nums[index] < nums[index + 1]) {
index++;
}

int result = -1;
if (index == length - 1) {
result = search(nums, 0, length - 1, target);
} else if (index == 0) {
result = nums[0] == target ? 0 : search(nums, 1, length - 1, target);
} else if (nums[index] < target || nums[index + 1] > target) {
} else if (nums[0] <= target) {
result = search(nums, 0, index, target);
} else {
result = search(nums, index + 1, length - 1, target);
}

return result;
}

private int search(int[] nums, int begin, int end, int target) {
if (begin > end) {
return -1;
}

int mid = (begin + end) / 2;
int value = nums[mid];
if (value > target) {
return search(nums, begin, mid - 1, target);
} else if (value == target) {
return mid;
} else {
return search(nums, mid + 1, end, target);
}
}


Solution2:

better

public int search(int[] A, int target) {
if (A.length == 0) {
return -1;
}
int lo = 0;
int hi = A.length - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (A[mid] == target)
return mid;

if (A[lo] <= A[mid]) {
if (target >= A[lo] && target < A[mid]) {
hi = mid - 1;
} else {
lo = mid + 1;
}
} else {
if (target > A[mid] && target <= A[hi]) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
}
return A[lo] == target ? lo : -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode