Created
April 29, 2021 11:47
-
-
Save vrat28/3067865c3ac5fb81e04457660927850c to your computer and use it in GitHub Desktop.
Find first and Last position using binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int[] searchRange(int[] N, int T) { | |
int Tleft = find(T, N, 0); | |
if (Tleft == N.length || N[Tleft] != T) return new int[] {-1, -1}; | |
return new int[] {Tleft, find(T+1, N, Tleft) - 1}; | |
} | |
public int find(int target, int[] arr, int left) { | |
int right = arr.length - 1; | |
while (left <= right) { | |
int mid = left + right >> 1; | |
if (arr[mid] < target) left = mid + 1; | |
else right = mid - 1; | |
} | |
return left; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment