땅지원
땅지원's Personal blog
땅지원
전체 방문자
오늘
어제
  • 전체 (353)
    • Frontend (2)
      • React (2)
    • Backend (90)
      • Java (16)
      • Python (19)
      • Spring (23)
      • Database (21)
      • Troubleshooting (8)
    • DevOps (27)
      • ELK (13)
    • CS (40)
    • OS (2)
      • Linux (2)
    • Algorithm (95)
      • concept (18)
      • Algorithm Problem (77)
    • 인공지능 (25)
      • 인공지능 (12)
      • 연구노트 (13)
    • 수업정리 (35)
      • 임베디드 시스템 (10)
      • 데이터통신 (17)
      • Linux (8)
    • 한국정보통신학회 (5)
      • 학술대회 (4)
      • 논문지 (1)
    • 수상기록 (8)
      • 수상기록 (6)
      • 특허 (2)
    • 삼성 청년 SW 아카데미 (6)
    • 42seoul (12)
    • Toy project (3)
    • 땅's 낙서장 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • 20.11.6 BB21플러스 온라인 학술대회
  • 20.10.30 한국정보통신학회 온라인 학술대회

인기 글

태그

  • I
  • 이것이 리눅스다 with Rocky Linux9
  • E
  • ㅗ
  • D

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
땅지원
Algorithm/Algorithm Problem

10816 숫자 카드 2(Hashmap, Counter)

Algorithm/Algorithm Problem

10816 숫자 카드 2(Hashmap, Counter)

2022. 4. 2. 16:42

https://www.acmicpc.net/problem/10816

 

10816번: 숫자 카드 2

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,

www.acmicpc.net

<방법 1 : 단순 리스트 탐색>

#단순 리스트 탐색

n = int(input())
data1 = list(map(int,input().split()))

m = int(input())
data2 = list(map(int,input().split()))

for i in data2:
    temp = data1.count(i)
    print(temp, end=' ')

N과 M이 500,000이기 때문에 단순 리스트 탐색을 이용하면 시간복잡도에서 N^2가 되므로 당연히 시간초과가 난다.

 

 

<방법 2 : 이진 탐색>

#이진 탐색 이용

n = int(input())
data1 = list(map(int,input().split()))

m = int(input())
data2 = list(map(int,input().split()))
data1.sort()

def binary_search(array, target, start, end):
    if start > end:
        return None
    mid = (start + end) // 2
    if array[mid] == target:
        return array[start:end+1].count(target)
    elif array[mid] < target:
        return binary_search(array, target, mid+1, end)
    else:
        return binary_search(array, target, start, mid-1)

for i in range(len(data2)):
    a = binary_search(data1, data2[i], 0, len(data1)-1)
    if not a == None:
        print(a, end=' ')
    else:
        print(0, end=' ')

이진탐색을 이용해도 시간초과가 나서 내장 모듈을 이용하는 방법을 택하기로 했다.

 

 

<방법 3 : Counter 내장모듈 이용>

#Counter 이용

n = int(input())
data1 = list(map(int,input().split()))

m = int(input())
data2 = list(map(int,input().split()))

from collections import Counter
count = Counter(data1)
print(count)

for i in range(len(data2)):
    if data2[i] in count:
        print(count[data2[i]], end=' ')
    else:
        print(0, end=' ')

 

Counter 내장모듈의 시간복잡도는 O(N)이기 때문에 시간에 맞춰 탐색이 가능했다.

 

 

<방법 4 : 이진탐색 bisect 내장모듈 이용>

#bisect 내장모듈 이용

import sys
input = sys.stdin.readline

n = int(input())
data1 = list(map(int,input().split()))

m = int(input())
data2 = list(map(int,input().split()))
data1.sort()

from bisect import bisect_left, bisect_right

def count_by_range(a, left_value, right_value):
    right_index = bisect_right(a, right_value)
    left_index = bisect_left(a, left_value)
    return right_index - left_index


for i in range(len(data2)):
    print(count_by_range(data1, data2[i], data2[i]), end=' ')

 

<방법 5 : Hashmap(Dictionary) 이용>

#Hashmap

import sys
input = sys.stdin.readline

n = int(input())
data1 = list(map(int,input().split()))

m = int(input())
data2 = list(map(int,input().split()))

hash = {}

for i in data1:
    if i in hash:
        hash[i] += 1
    else:
        hash[i] = 1

for i in data2:
    if i in hash:
        print(hash[i], end=' ')
    else:
        print(0, end=' ')

HashTable(해시 테이블)은 Key 와 Value 의 쌍으로 데이터를 저장하는 자료구조 입니다.
언어에 따라서 HashMap이라고도 불리며, 파이썬의 Dictionary 또한 HashTable로 구현되어 있습니다.

HashTable(HashMap, Dictionary)의 특징은 다음과 같습니다.

  • 순차적으로 데이터를 저장하지 않습니다.
  • Key를 통해서 Value값을 얻습니다.
  • Value값은 중복가능 하지만 Key는 중복될 수 없습니다.
  • 수정 가능합니다.(mutable)

파이썬의 List나 자바스크립트의 Array(list)와 달리 저장된 데이터를 순차적으로 찾는게 아니고,
Key값을 통해서 Value값을 찾기 때문에 빠릅니다.

'Algorithm > Algorithm Problem' 카테고리의 다른 글

프로그래머스 쿼드압축 후 개수 새기(분할 정복)  (0) 2022.04.14
백준 18243 Small World Network(플로이드-와샬, BFS)  (0) 2022.04.07
백준 1764 듣보잡(set() 자료형)  (0) 2022.03.26
백준 1780 종이의 개수  (0) 2022.03.06
백준 2667 단지번호붙이기(BFS, DFS)  (0) 2022.03.06
    'Algorithm/Algorithm Problem' 카테고리의 다른 글
    • 프로그래머스 쿼드압축 후 개수 새기(분할 정복)
    • 백준 18243 Small World Network(플로이드-와샬, BFS)
    • 백준 1764 듣보잡(set() 자료형)
    • 백준 1780 종이의 개수
    땅지원
    땅지원
    신입 개발자의 우당탕탕 기술 블로그

    티스토리툴바

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.