일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Medium
- leetcode
- Bellman-Ford
- BFS
- SinglyLinkedList
- sorting
- Union Find
- greedy
- 광연자동차운전면허학원
- VCS
- heap
- 자료구조
- String
- hash
- 구현
- Hashtable
- graph
- Two Pointers
- stack
- dfs
- Java
- hash table
- python3
- LinkedList
- Leedcode
- DailyLeetCoding
- A* Algorithm
- ArrayList vs LinkedList
- array
- Easy
Archives
- Today
- Total
Min IT's Devlog
[python3] 35. Search Insert Position 본문
풀이 일자: 23.02.20
난이도: [Easy]
분류: [Binary Search]
문제 내용
정렬된 배열과 target이 주어졌을 때 해당 target이 정렬에 있다면 그 위치를 return하고 정렬에 없다면 들어가야 하는 위치를 return하는 문제였고 반드시 logN의 시간복잡도를 가지는 알고리즘을 쓰라고 했다.
문제 해결 흐름
1. Linear하게도 풀 수 있고 Binary로 풀 수 있는데 시간복잡도에 대한 제약조건이 존재하므로 Binary만 가능하겠다.
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left = 0; right= len(nums) - 1;
while(left <= right):
mid = (left + right)//2;
if nums[mid] == target:
return mid;
elif nums[mid] < target:
left = mid + 1;
else:
right = mid - 1;
return left;
Time Complexity: O(logN)
시간복잡도는 이진탐색의 시간복잡도인 logN을 가지게 된다.
Space Complexity: O(1)
left와 right외의 다른 변수를 사용하지 않기 때문에 공간복잡도는 1이다.
다른 해결 방식
1. 이번에는 파이썬에서 제공하는 라이브러리 함수를 사용해보자.
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect.bisect_left(nums, target);
=> 내가 작성했던 binarySearch와 같은 방식으로 작동하는 bisect_left라는 함수를 사용하였다.
문제 링크
https://leetcode.com/problems/search-insert-position/description/
'코테 > LeetCode(Solve)' 카테고리의 다른 글
[python3] 1011. Capacity To Ship Packages Within D Days (0) | 2023.02.22 |
---|---|
[python3] 540. Single Element in a Sorted Array (0) | 2023.02.21 |
[python3] 226. Invert Binary Tree (0) | 2023.02.18 |
[python3] 783. Minimum Distance Between BST Nodes (0) | 2023.02.17 |
[python3] 104. Maximum Depth of Binary Tree (0) | 2023.02.16 |
Comments