Python/[Algorithm] 알고리즘
[Q2:English] First and last index in sorted array
Kamea
2022. 6. 2. 15:47
👇🏻 문제(이 정도는 해석X...귀찮,, 영어강의라 포스트도 영어로)
Given a sorted array of integers arr and an integer target, find the index of the first and last position of target in arr. In targer can't be found in arr, return [-1,-1].
For example, arr = [2,4,5,5,5,5,5,7,9,9], target = 5 👉🏻 output : [2, 6]
[Method 1]
# Logic
# Code
# Complexity
S(n) = O(1)
T(n) = O(n)
[Method 2]
How about using binary search? Because it is sorted already.
2022.05.18 - [Python/[Algorithm] 알고리즘] - Binary Search, 이진 탐색
Binary Search, 이진 탐색
이진탐색은 정렬된 배열 안에서 타깃 값의 인덱스를 찾는 탐색 알고리즘이다. 이진탐색은 배열의 중간 인덱스의 값을 타깃 값과 비교해 타깃 값의 인덱스를 찾는다. 1. 문제 상황 문제 상황을
sennieworld.tistory.com
# Logic
1️⃣ Find first position
2️⃣ Find last position using first position
Set last_idx = first_idx and Check with while loop.
or
Find with binary search like finding first position.
# Code
# Complexity
T(n) = 2 * O(logn) = O(logn)
S(n) = O(1)