일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- datacamp
- delete join
- docker container
- airflow webserver
- Dynamic Programming
- airflow architecture
- 데이터 엔지니어
- 백준 온라인 저지
- Pseudo Lab
- data_engineer
- 2023년 목표
- terraform
- hackerrank
- 백준온라인저지
- Airflow
- MySQL
- dsf
- Spark
- 알고리즘
- Python
- 그리디
- BOT
- docker
- SQL
- 프로그래머스
- 빅데이터를 지탱하는 기술
- leetcode
- Data Engineering
- docker image
- telegram
Archives
- Today
- Total
Lim Seunghyun Space
[Leetcode] Search Insert Position 본문
문제 출처
Search Insert Position - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 해설
- 오름차순으로 정렬된 리스트(nums)에 순서를 유지하면서 정수(target)가 들어갈 수 있는 위치를 찾는 문제
- 시간 복잡도는 O(log n)가 되도록 코드를 구성
문제 풀이
# source: https://leetcode.com/problems/search-insert-position/?envType=study-plan&id=binary-search-i
class Solution:
def searchInsert(self, nums: list, target: int) -> int:
start = 0
end = len(nums) - 1
while start <= end:
mid = (end + start) // 2
point = nums[mid]
if point == target:
return mid
if point > target:
end = mid - 1
elif point < target:
start = mid + 1
return start
- 삽입할 위치를 탐색하는데 시간복잡도가 O(log n)이 되어야하고 nums가 오름차순으로 정렬되어 제공되기 때문에 이진 탐색으로 접근
- 기존 이진 탐색과는 다르게 마지막까지 탐색해서 target이 삽입할 인덱스를 구해야하므로 함수 마지막에 start를 반환하는 로직을 추가하였다.
Github
728x90
'Algorithm > 문제' 카테고리의 다른 글
[Leetcode] Valid Perfect Sqaure (0) | 2022.11.26 |
---|---|
[Leetcode] Peak Index in a Mountain Array (0) | 2022.11.26 |
[Leetcode] Guess Number Higher or Lower (0) | 2022.11.24 |
[Leetcode] Binary Search (0) | 2022.11.23 |
[Leetcode] Reverse Integer (0) | 2022.11.21 |