33. Search in Rotated Sorted Array

202407011930
tags: #binary-search

var search = function(nums, target) {
	let start = 0;
	let end = nums.length - 1;
	while (start <= end) {
		const mid = Math.floor((end - start) / 2) + start;
		if (nums[mid] === target) {
			return mid;
		}
		if (nums[start] <= nums[mid]) {
			if (nums[start] <= target && target < nums[mid]) {
				end = mid - 1;
			} else {
				start = mid + 1;
			}
		} else {
			if (nums[mid] < target && target <= nums[end]) {
				start = mid + 1;
			} else {
				end = mid - 1;
			}
		}
	}
	return -1;
};

Reference

https://leetcode.com/problems/search-in-rotated-sorted-array/