Skip to content

Commit

Permalink
solution(cpp,python): 34. Find First and Last Position of Element in...
Browse files Browse the repository at this point in the history
34. Find First and Last Position of Element in Sorted Array
  • Loading branch information
godkingjay authored Oct 11, 2023
2 parents b15b164 + 407f463 commit 1a7cf5a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
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;
}
};
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

0 comments on commit 1a7cf5a

Please sign in to comment.