1 file9 days ago
1

/**

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { let n = nums.length; let pivot = binarySearchCustome(nums, 0, n - 1); console.log({pivot}); if (pivot === -1) { return binarySearch(nums, 0, n - 1, target); } if (nums[pivot] === target) { return pivot; } if (target > nums[pivot] && target <= nums[n-1]) { return binarySearch(nums, pivot, n - 1, target); } else { return binarySearch(nums, 0, pivot - 1, target); } return -1 }; var binarySearch = function(nums, low, high, target) { let pivot = Math.floor((low + high) / 2); while (low < high) { if (nums[pivot] === target) { return pivot; } if (nums[pivot] < target) { low = pivot + 1 pivot = Math.floor((low + high) / 2); } else { high = pivot; pivot = Math.floor((low + high) / 2); } } return -1 } var binarySearchCustome = function(nums, low, high) { if (nums.length === 2 || nums.length === 1) { return -1; } let pivot = Math.floor((low + high) / 2); while (low < high) { if (nums[pivot] < nums[pivot-1] && nums[pivot] < nums[pivot+1]) { return pivot; } if (nums[pivot] > nums[high] && nums[low] > nums[high]) { low = pivot + 1; pivot = Math.floor((low + high) / 2); } if (nums[pivot] > nums[low] && nums[high] > nums[low]) { high = pivot; pivot = Math.floor((low + high) / 2); } if (nums[pivot] < nums[low] && nums[high] < nums[low]) { high = pivot; pivot = Math.floor((low + high) / 2); } } }