알고리즘/leetcode
35. Search Insert Position
1.5볼트
2023. 2. 20. 13:59
728x90
Given a sorted array of distinct integers 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.
You must write an algorithm with O(log n) runtime complexity.
개별 정수의 정렬된 배열과 대상 값이 주어지면 대상이 발견되면 인덱스를 반환합니다. 그렇지 않은 경우 순서대로 삽입된 인덱스를 반환합니다.
O(log n)런타임 복잡성이 있는 알고리즘을 작성해야 합니다 .
이진탐색을 이용해 숫자를 삽입하는 인덱스를 찾는문제
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
a=0
b=len(num)-1
if a>=target:
return 0
elif b<=target:
return b+1
while True:
c=(a+b)//2
if num[c]<target:
a=c+1
elif num[c]>target:
b=c-1
else:
return c
return c