Day21 搜尋旋轉排序陣列
阿新 • • 發佈:2021-02-16
技術標籤:LeetCode刷題集leetcode演算法資料結構
實際含義:在旋轉陣列中查詢某元素
升序排列的整數陣列 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:
輸入:nums = [4,5,6,7,0,1,2], target = 0
輸出:4
示例2:
輸入:nums = [4,5,6,7,0,1,2], target = 3
輸出:-1
示例3:
輸入:nums = [1], target = 0
輸出:-1
提示:
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums 中的每個值都 獨一無二
nums 肯定會在某個點上旋轉
-10^4 <= target <= 10^4
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;
}
}
官方解
-
二分查詢
我太年輕了,這是考查二分查詢的,我竟然沒有想到,菜
二分查詢注意判斷條件:在有序的半段中進行判斷,從而確定下次對半查詢的位置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; } }
-
時間複雜度: O(logn)
-
空間複雜度: O(1)
-