고구마와 감자
Amor DevFati(아모르 개발파티)
고구마와 감자
전체 방문자
오늘
어제
  • 분류 전체보기
    • 스프링
    • 알고리즘
      • 백준
      • 프로그래머스
      • 인프런_자바코테강의
      • 리트코드
      • 해커랭크
      • 코드업
      • 이것저것
    • 자바
    • GIT
    • 파이썬
    • 개발이론
    • JPA
    • 김영한 강의
      • 모든 개발자를 위한 HTTP 웹 기본 지식
      • 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술
      • 스프링 핵심 원리 - 기본편
    • 일기 및 아무말 적기

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 남욱이의 닭장
  • 2921
  • 11966
  • 2857
  • 5988
  • 홀수일까 짝수일까
  • 14656
  • 5361
  • 10409
  • 전투 드로이드 가격
  • 백준
  • 고려대학교에는 공식 와인이 있다
  • 더하기 3
  • 11023
  • 조교는 새디스트야!!
  • 1598
  • 2의 제곱인가
  • 16673
  • 꼬리를 무는 숫자 나열
  • Mini Fantasy War

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
고구마와 감자

Amor DevFati(아모르 개발파티)

알고리즘/리트코드

LeetCode 35.Search Insert Position (Python)

2022. 4. 17. 15:35

https://leetcode.com/problems/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

Solution 1 

  • 시간복잡도 : O(N)
  • 공간복잡도 : O(1)

아이디어 (Brute- Force)

배열을 0에서부터 순회하고, target의 값과 같거나 크다면 순회 중단하고 중단한 시점의 인덱스를 반환한다. 

# 1. Brute force
def searchInsert(nums: List[int], target: int) -> int:
    index = 0

    while index < len(nums):
        if target <= nums[index]:
            break

        index += 1

    return index

Solution 2

  • 시간복잡도 : O(logN)
  • 공간복잡도 : O(1)

아이디어(Hash Table)

해쉬(딕셔너리) 를 사용하는데 이진탐색으로 탐색 속도를 높인다. 

이진탐색을 접한 횟수가 많다보니 대하는 느낌이 확실히 편해졌다. 

 

def searchInsert(nums: List[int], target: int) -> int:
    low = 0
    high = len(nums) - 1

    while low <= high:
        mid = int((low+high) / 2)

        if target == nums[mid]:
            return mid
        if target > nums[mid]:
            low = mid + 1
        else:
            high = mid -1

    return low

'알고리즘 > 리트코드' 카테고리의 다른 글

LeetCode 88. Merge Sorted Array (Python)  (0) 2022.04.17
LeetCode 26. Remove Duplicates From Sorted Array (Python)  (0) 2022.04.17
LeetCode 1. Two Sum (Python)  (0) 2022.04.17
LeetCode 66 Plus One  (0) 2022.04.10
    '알고리즘/리트코드' 카테고리의 다른 글
    • LeetCode 88. Merge Sorted Array (Python)
    • LeetCode 26. Remove Duplicates From Sorted Array (Python)
    • LeetCode 1. Two Sum (Python)
    • LeetCode 66 Plus One
    고구마와 감자
    고구마와 감자
    Amor DevFati는 김연자-Amor Fati에 Development(개발)의 Dev 를 첨가하여 만든 이름

    티스토리툴바