Skip to content

Commit 6a6f921

Browse files
committed
Add solution #33
1 parent dfa0a58 commit 6a6f921

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
27|[Remove Element](./0027-remove-element.js)|Easy|
3030
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
3131
31|[Next Permutation](./0031-next-permutation.js)|Medium|
32+
33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium|
3233
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
3334
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
3435
42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 33. Search in Rotated Sorted Array
3+
* https://leetcode.com/problems/search-in-rotated-sorted-array/
4+
* Difficulty: Medium
5+
*
6+
* There is an integer array nums sorted in ascending order (with distinct values).
7+
*
8+
* Prior to being passed to your function, nums is possibly rotated at an unknown pivot
9+
* index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1],
10+
* ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7]
11+
* might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
12+
*
13+
* Given the array nums after the possible rotation and an integer target, return the index
14+
* of target if it is in nums, or -1 if it is not in nums.
15+
*
16+
* You must write an algorithm with O(log n) runtime complexity.
17+
*/
18+
19+
/**
20+
* @param {number[]} nums
21+
* @param {number} target
22+
* @return {number}
23+
*/
24+
var search = function(nums, target) {
25+
let start = 0;
26+
let end = nums.length;
27+
28+
while (start < end) {
29+
const i = Math.floor((start + end) / 2);
30+
const middle = nums[i] < nums[0] === target < nums[0]
31+
? nums[i]
32+
: target < nums[0] ? -Infinity : Infinity;
33+
34+
if (middle < target) {
35+
start = i + 1;
36+
} else if (middle > target) {
37+
end = i;
38+
} else {
39+
return i;
40+
}
41+
}
42+
43+
return -1;
44+
};

0 commit comments

Comments
 (0)