在旋转有序数组中找出给定的一个整数,并返回该整数在数组中的下标?
//常规有序数组
int[] arr1 = {1,2,3,4,5}
//旋转有序数组
int[] arr2 = {50,60,70,80,20,30,40}
解题思路:
- 假设最左边下标用left标识,最右边下标有right标识,中间整数下标用mid标识;
- 每次判断下标mid对应的整数值是否大于下标left对应整数值,如果大于,说明左边有序,如果小于,说明右边有序;
- 在上一步的基础上,如果左边有序,判断目标值target实在左边还是在右边,如果在左边,right = mid-1,否则 left = mid+1;
- 如果右边有序,判断目标值target在左边还是右边,如果在右边,left = mid+1,否则 right = mid -1
代码如下:
public class Solution_2 {
private static int findTargetIndex(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = (right - left) / 2 + left;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] > nums[left]) {
//说明在左侧有序
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
//说明在右侧有序
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 1, 2, 3, 4, 5, 6,7};
int target = 2;
int targetIndex = findTargetIndex(arr, target);
System.out.println("targetIndex = " + targetIndex);
}
}
原文地址:https://www.cnblogs.com/it-cj/p/11399329.html
时间: 2024-10-22 12:53:17