1
- /**
2
- * Finds the first and last occurrence of a target value in a sorted array.
3
- *
4
- * @param {number[] } N - The sorted array of numbers.
5
- * @param {number } T - The target value to search for.
6
- * @returns {number[] } An array containing the first and last index of the target value, or [-1,-1] if not found.
7
- */
8
- const searchRange = function ( N , T ) {
9
- // Helper function to perform binary search on the array
10
- const find = ( target , arr , left = 0 , right = arr . length ) => {
11
- while ( left <= right ) {
12
- // Calculate the middle index
13
- let mid = left + right >> 1 ;
14
- // If the middle element is less than the target, move the left pointer to mid + 1
15
- if ( arr [ mid ] < target ) left = mid + 1 ;
16
- // If the middle element is greater than or equal to the target, move the right pointer to mid - 1
17
- else right = mid - 1 ;
18
- }
19
- // Return the left pointer, which will be the index of the target or the insertion point if not found
20
- return left ;
21
- } ;
22
-
23
- // Find the leftmost index of the target value
24
- let Tleft = find ( T , N ) ;
25
- // If the target value is not found in the array, return [-1,-1]
26
- if ( N [ Tleft ] !== T ) return [ - 1 , - 1 ] ;
27
- // Find the rightmost index of the target value
28
- return [ Tleft , find ( T + 1 , N , Tleft ) - 1 ] ;
29
- } ;
1
+ /**
2
+ * Finds the first and last occurrence of a target value in a sorted array.
3
+ *
4
+ * @param {number[] } N - The sorted array of numbers.
5
+ * @param {number } T - The target value to search for.
6
+ * @returns {number[] } An array containing the first and last index of the target value, or [-1,-1] if not found.
7
+ */
8
+ const searchRange = function ( N , T ) {
9
+ // Helper function to perform binary search on the array
10
+ const find = ( target , arr , left = 0 , right = arr . length ) => {
11
+ while ( left <= right ) {
12
+ // Calculate the middle index
13
+ let mid = left + right >> 1 ;
14
+ // If the middle element is less than the target, move the left pointer to mid + 1
15
+ if ( arr [ mid ] < target ) left = mid + 1 ;
16
+ // If the middle element is greater than or equal to the target, move the right pointer to mid - 1
17
+ else right = mid - 1 ;
18
+ }
19
+ // Return the left pointer, which will be the index of the target or the insertion point if not found
20
+ return left ;
21
+ } ;
22
+
23
+ // Find the leftmost index of the target value
24
+ let Tleft = find ( T , N ) ;
25
+ // If the target value is not found in the array, return [-1,-1]
26
+ if ( N [ Tleft ] !== T ) return [ - 1 , - 1 ] ;
27
+ // Find the rightmost index of the target value
28
+ return [ Tleft , find ( T + 1 , N , Tleft ) - 1 ] ;
29
+ } ;
30
30
0 commit comments