Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
if (nums.length === 1) return nums[0] === target ? 0 : -1;

// 정렬
let start = 0;
if (nums[0] > nums[nums.length - 1]) {
while (nums[start] < nums[start+1]) start++;
start++;
nums = [...nums.slice(start), ...nums.slice(0, start)];
}

// 절반씩 잘라가며 찾기
var _search = (arr, startIndexOfOrigin) => {
const { length: l } = arr;
if (l === 0) return -1;
if (l === 1) return arr[0] === target ? startIndexOfOrigin : -1;

const m = Math.floor(l / 2);
if (arr[m] < target) {
return _search(arr.slice(m + 1), startIndexOfOrigin + m + 1);
} else if (arr[m] === target) {
return startIndexOfOrigin + m;
} else {
return _search(arr.slice(0, m), startIndexOfOrigin);
}
}

const v = _search(nums, 0);
return v === -1 ? -1 : start === 0 ? v : (v + start) % nums.length;
};
37 changes: 37 additions & 0 deletions yeongrok/0033-search-in-rotated-sorted-array/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<h2><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">33. Search in Rotated Sorted Array</a></h2><h3>Medium</h3><hr>Can you solve this real interview question? Search in Rotated Sorted Array - There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.



Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4


Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1


Example 3:

Input: nums = [1], target = 0
Output: -1




Constraints:

* 1 <= nums.length <= 5000
* -104 <= nums[i] <= 104
* All values of nums are unique.
* nums is an ascending array that is possibly rotated.
* -104 <= target <= 104