Skip to content

Commit 0fb0065

Browse files
author
Kohei Asai
authored
33. Search in Rotated Sorted Array (#81)
1 parent 7556274 commit 0fb0065

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import search from "./searchInRotatedSortedArray";
2+
3+
describe("33. Search in Rotated Sorted Array", () => {
4+
test("#1", () => {
5+
expect(search([4, 5, 6, 7, 0, 1, 2], 0)).toBe(4);
6+
});
7+
8+
test("#2", () => {
9+
expect(search([4, 5, 6, 7, 0, 1, 2], 3)).toBe(-1);
10+
});
11+
12+
test("#3", () => {
13+
expect(search([4, 5, 6, 7, 0, 1, 2], 4)).toBe(0);
14+
});
15+
16+
test("#4", () => {
17+
expect(search([3, 1], 3)).toBe(0);
18+
});
19+
20+
test("#5", () => {
21+
expect(search([7, 8, 1, 2, 3, 4, 5, 6], 2)).toBe(3);
22+
});
23+
});
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 33. Search in Rotated Sorted Array
2+
// https://leetcode.com/problems/search-in-rotated-sorted-array/
3+
export default function search(nums: number[], target: number): number {
4+
// check if the target value is inside a range that may be rotated
5+
function isInRangeMaybeRotated(from: number, to: number) {
6+
const fromValue = nums[from];
7+
const toValue = nums[to];
8+
9+
// the range is looped when the from value is greater than the to value
10+
if (fromValue > toValue) return target >= fromValue || target <= toValue;
11+
12+
// when the range is not looped, target must be between the from value and the to value
13+
return target >= fromValue && target <= toValue;
14+
}
15+
16+
let from = 0;
17+
let to = nums.length;
18+
19+
while (from < to) {
20+
const middle = Math.floor((from + to) / 2);
21+
22+
if (nums[middle] === target) return middle;
23+
24+
if (isInRangeMaybeRotated(from, middle - 1)) {
25+
to = middle;
26+
} else {
27+
from = middle + 1;
28+
}
29+
}
30+
31+
return -1;
32+
}

0 commit comments

Comments
 (0)