algorighm/top-interview-leetcode150/binary-search/33搜索旋转排序数组.js

47 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
const search = function (nums, target) {
};
/*
思路:按照题目描述,数组旋转之后会变成两段有序的序列,而且第一段有序序列一定是大于第二段有序序列的
可以直接利用二分查找但是在查找的时候要留意mid落在那一段序列上如果落在第一段序列上 nums[mid] >= nums[left],
反之第二段知道mid落在那一段序列之后我们还需判断target在那一段序列上如果mid在第一段target也在第一段并且
小于nums[mid]收缩右边界为mid-1如果在第二段收缩左边界为mid+1
*/
function f1(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = left + ((right - left) >> 1);
if (nums[mid] === target) {
return mid; // 找到目标值,直接返回
}
// 如果mid落在第一段那么nums[mid] >= nums[0], 否则落在第二段
if (nums[mid] >= nums[0]) {
// 如果target在第一段,并且target < nums[mid]
if (target > -nums[0] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
// 如果target落在第二段并且target > nums[mid]
// eslint-disable-next-line no-lonely-if
if (target <= nums[nums.length - 1] && target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1; // 没有找到目标值
}