티스토리 뷰

반응형

Question

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

 

Solution

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
       return 

 

1일1깡 방법

if target in nums:
	return nums.index(target)
else:
    nums.append(target)
    nums.sort()

return nums.index(target)

 

Binary Search 

low = 0
high = len(nums) - 1
while low <= high:
	mid = (low + high) // 2
if target <= nums[mid]:
	high = mid - 1
else:
	low = mid + 1
   
return low

bisect [link]

return bisect.bisect_left(nums, target)

time complexity, space complexity 모두 bisect가 압도한다...

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함
반응형