实际含义:在旋转数组中查找某元素
升序排列的整数数组 nums 在预先未知的某个点上进行了旋转(例如, [0,1,2,4,5,6,7] 经旋转后可能变为 [4,5,6,7,0,1,2] )。请你在数组中搜索 target ,如果数组中存在这个目标值,则返回它的索引,否则返回 -1
https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
示例1:
示例2:
示例3:
提示:
Java解法
package sj.shimmer.algorithm.ten_3;
/**
* Created by SJ on 2021/2/14.
*/
class D21 {
public static void main(String[] args) {
System.out.println(search2(new int[]{4,5,6,7,8,1,2,3}, 8));
// System.out.println(search(new int[]{4, 5, 6, 7, 0, 1, 2}, 4));
// System.out.println(search2(new int[]{4, 5, 6, 7, 0, 1, 2}, 0));
// System.out.println(search2(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));
}
public static int search(int[] nums, int target) {
int index = -1;
for (int i = 0; i < nums.length; i++) {
if (target == nums[i]) {
index = i;
break;
}
}
return index;
}
public static int search2(int[] nums, int target) {
int length = nums.length;
if (length ==1&&nums[0]==target) {
return 0;
}
int start = 0;
int end = length -1;
while (start<=end) {
int mid = (end+start) / 2;
if (nums[mid]==target) {
return mid;
}
if (nums[0] <= nums[mid]) {
if (nums[0] <= target && target < nums[mid]) {
//正常升序且包含
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (nums[mid] < target && target <= nums[length - 1]) {
//后半段正常升序且包含
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return -1;
}
}
官方解
-
二分查找
时间复杂度: O(logn)
空间复杂度: O(1)