Solution uses a modified version of Binary Search.
Javascript (ES6)
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
const search = (nums, target) => {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (nums[mid] === target) {
return mid;
}
if (nums[low] <= nums[mid]) {
// Left half is sorted.
if (target >= nums[low] && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
// Right half is sorted.
if (target > nums[mid] && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
};
console.log(search([4, 5, 1, 2, 3], 2)); // 3
Demo
Java
Time: O(nlogn)
Space: O(1)
class Solution { public int search(int[] nums, int target) { int low = 0, high = nums.length - 1; int mid; while (low <= high) { mid = low + (high - low) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < nums[high]) { if (target > nums[mid] && target <= nums[high]) low = mid + 1; else high = mid - 1; } else { if (target >= nums[low] && target < nums[mid]) high = mid - 1; else low = mid + 1; } } return -1; } }