-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solution(cpp,python): 34. Find First and Last Position of Element in...
34. Find First and Last Position of Element in Sorted Array
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
25 changes: 25 additions & 0 deletions
25
Hard/34. Find First and Last Position of Element in Sorted Array/sol.cpp
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
#include <vector> | ||
|
||
class Solution { | ||
public: | ||
std::vector<int> searchRange(std::vector<int>& N, int T) { | ||
int Tleft = find(T, N, 0); | ||
if (Tleft == N.size() || N[Tleft] != T) { | ||
return {-1, -1}; | ||
} | ||
return {Tleft, find(T + 1, N, Tleft) - 1}; | ||
} | ||
|
||
int find(int target, std::vector<int>& arr, int left) { | ||
int right = arr.size() - 1; | ||
while (left <= right) { | ||
int mid = left + (right - left) / 2; | ||
if (arr[mid] < target) { | ||
left = mid + 1; | ||
} else { | ||
right = mid - 1; | ||
} | ||
} | ||
return left; | ||
} | ||
}; |
16 changes: 16 additions & 0 deletions
16
Hard/34. Find First and Last Position of Element in Sorted Array/sol.py
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
class Solution: | ||
def searchRange(self, N, T): | ||
Tleft = self.find(T, N, 0) | ||
if Tleft == len(N) or N[Tleft] != T: | ||
return [-1, -1] | ||
return [Tleft, self.find(T + 1, N, Tleft) - 1] | ||
|
||
def find(self, target, arr, left): | ||
right = len(arr) - 1 | ||
while left <= right: | ||
mid = (left + right) // 2 | ||
if arr[mid] < target: | ||
left = mid + 1 | ||
else: | ||
right = mid - 1 | ||
return left |