본문 바로가기

자료구조,알고리즘

LeetCode-35 Search Insert Position 파이썬 풀이

 

Search Insert Position - LeetCode

Can you solve this real interview question? Search Insert Position - 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 w

leetcode.com

문제

정렬된 int형 배열에서 target과 같은 값이 있다면 해당 값이 위치하는 인덱스를, 없다면 target이 어느 인덱스에 들어가야 하는 지를 반환하는 문제입니다. 문제 그 자체가 이진 탐색인 문제라서 이진 탐색만 구현하면 됩니다.

풀이

1. 배열의 가장 처음과 끝 인덱스를 더한후 반으로 나누어 배열의 중간 인덱스를 찾습니다.

2. 배열의 중간 인덱스에 위치한 값이 찾으려는 값보다 작으면 [배열 처음 ~ 배열 중간]을 크다면 [배열 중간 ~ 배열 끝]을 다시 조회합니다.

3. 찾으려는 값을 조회했다면 해당 인덱스를 반환합니다.

4. 끝까지 찾지 못하였다면 탐색 실패한 위치를 반환합니다.

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        start = 0
        end = len(nums) - 1

        while start <= end:
            mid = ( start + end ) // 2

            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                end = mid - 1
            else:
                start = mid + 1
        return start