题目:https://leetcode.com/problems/search-in-rotated-sorted-array/
思路:
题目要求时间复杂度必须是 O(log n) 级别,所以用了二分查找
首先是使用二分查找,查找出数组中的转折点下标position,然后在position处对数组进行二分查找,查找出target的下标
解题:
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
if (nums.length == 1) {
if (nums[0] == target) {
return 0;
} else {
return -1;
}
}
//二分法查找中间转折点的下标
int postion = -1;//转折点下标
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid != left && nums[mid] < nums[mid - 1]) {
postion = mid - 1;
break;
}
if (mid != right && nums[mid] > nums[mid + 1]) {
postion = mid;
break;
}
if (nums[mid] < nums[left]) {//转折点在左侧范围,将right值修改
right = mid - 1;
} else {//转折点在右侧范围,将left值修改
left = mid + 1;
}
}
//使用二分法查找数据,从转折点的位置开始分开
if (postion == -1) {//数组中没有转折点,数组是升序
postion = findIndex(nums, 0, nums.length - 1, target);
} else {//有转折点
if (nums[postion] == target) {
return postion;
}
if (target < nums[0]) {
postion = findIndex(nums, postion + 1, nums.length - 1, target);
} else {
postion = findIndex(nums, 0, postion - 1, target);
}
}
return postion;
}
/**
* 从升序数组中找到target的index
*
* @param nums
* @param target
* @return
*/
public int findIndex(int[] nums, int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
网友评论