Java for LeetCode 033 Search in Rotated Sorted Array

时间:2022-08-14 21:08:49

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.

解题思路:

Tag中已经有提示用二分查找,关键是确定target在左半部分还是右半部分,建议画个图,能直观很多。

JAVA实现如下:

	static public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
if (target == nums[(right + left) / 2])
return (right + left) / 2;
//右半部分为旋转区域
if (nums[(right + left) / 2] >= nums[left]) {
if (target >= nums[left] && target < nums[(right + left) / 2])
right = (right + left) / 2 - 1;
else
left = (right + left) / 2 + 1;
}
//左半部分为旋转区域
else {
if (target > nums[(right + left) / 2] && target <= nums[right])
left = (right + left) / 2 + 1;
else
right = (right + left) / 2 - 1;
}
}
return -1;
}