File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time complexity: O(logn)
2
+ // Space complexity: O(1)
3
+
4
+ /**
5
+ * @param {number[] } nums
6
+ * @param {number } target
7
+ * @return {number }
8
+ */
9
+ var search = function ( nums , target ) {
10
+ let left = 0 ;
11
+ let right = nums . length - 1 ;
12
+
13
+ while ( left <= right ) {
14
+ const mid = Math . floor ( ( left + right ) / 2 ) ;
15
+
16
+ if ( nums . at ( mid ) === target ) {
17
+ return mid ;
18
+ }
19
+
20
+ // rotate 된 구간이 있을 때
21
+ if ( nums . at ( mid + 1 ) > nums . at ( right ) ) {
22
+ if ( nums . at ( right ) >= target || nums . at ( mid + 1 ) <= target ) {
23
+ left = mid + 1 ;
24
+ continue ;
25
+ }
26
+
27
+ right = mid - 1 ;
28
+ continue ;
29
+ }
30
+
31
+ if ( target >= nums . at ( mid + 1 ) && target <= nums . at ( right ) ) {
32
+ left = mid + 1 ;
33
+ continue ;
34
+ }
35
+
36
+ right = mid - 1 ;
37
+ }
38
+
39
+ return - 1 ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments