ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 뒤에 있는 큰 수 찾기
    코딩 테스트/Level 2 2023. 1. 28. 20:59
    반응형

    https://school.programmers.co.kr/learn/courses/30/lessons/154539

    def solution(numbers):
        answer = []
        for i in range(len(numbers)):
            for j in range(i + 1, len(numbers)):
                if numbers[j] > numbers[i]:
                    answer.append(numbers[j])
                    break
            else:
                answer.append(-1)
        return answer

    뭐 당연히 이런 코드로는 통과 불능... 
    예전 Level 2의 수준과 다르게 어려워 졌다. ㅜ,.ㅜ

    편법이지만 뒤집어 생각하면 통과는 가능하다. 

    def solution(numbers):
        answer = [-1 for _ in numbers]
        for i in range(len(numbers) - 1, -1, -1):
            for j in range(i - 1, -1, -1):
                if numbers[j] >= numbers[i]:
                    break
                answer[j] = numbers[i]
        return answer

    힙을 써야한다. 

    from heapq import heappop, heappush
    
    
    def solution(numbers):
        answer = [-1 for _ in numbers]
        heap = []
        for i, each in enumerate(numbers):
            while heap and heap[0][0] < each:
                _, index = heappop(heap)
                answer[index] = each
            heappush(heap, (each, i))
        return answer
    반응형
Designed by Tistory.