[210206 TIL] Programmers Algorithm(스택/큐, 정렬)

602go·2021년 2월 7일
0

Algorithm

목록 보기
5/6
post-thumbnail

Today I Learned

written by 602



Programmers) 스택/큐 01. 주식가격

  1. 큐 적용 안한 버전
def solution(prices):
    answer = [0] * len(prices)

    for i in range(len(prices)-1):
        for j in range(i, len(prices)-1):
            if prices[i] >prices[j]:
                break
            else:
                answer[i] +=1
                
    return answer

이중 for문으로도 시간 제한에 걸리지 않고 통과되었다.

  1. 큐 적용한 버전
from collections import deque

def solution(prices):
    answer = []
    queue = deque(prices)
    
    while queue :
        price = queue.popleft()
        time = 0
        for n in queue :
            time += 1
            if price > n :
                break
        answer.append(time)
        
    return answer

파이썬에서 큐를 구현하기 위해서는 collections에서 deque를 불러 와야 한다.


Programmers) 정렬 03. H-Index

def solution(citations):
    citations.sort()
    n_cit = len(citations)
    
    for i in range(n_cit):
        ### 논문이 인용된 횟수 >= 인용된 논문의 개수
        if citations[i] >= n_cit-i:
            return n_cit-i
        
    return 0


0개의 댓글