Development/Algorithm
[Programmers] Lv.3 이중우선순위큐 (Go)
thisisnew
2022. 11. 26. 21:43
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/42628
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.

이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
Solution
import (
"errors"
"sort"
"strconv"
"strings"
)
const InsertOperation = "I"
const RemoveMax = "1"
type Operation struct {
Items []int
IsSorted bool
}
func (o *Operation) push(v string) {
x, _ := strconv.Atoi(v)
o.Items = append(o.Items, x)
o.IsSorted = false
}
func (o *Operation) Max() int {
if len(o.Items) == 0 {
return 0
}
if !o.IsSorted {
o.sort()
}
return o.Items[len(o.Items)-1]
}
func (o *Operation) Min() int {
if len(o.Items) == 0 {
return 0
}
if !o.IsSorted {
o.sort()
}
return o.Items[0]
}
func (o *Operation) removeMax() error {
if len(o.Items) == 0 {
return errors.New("empty items")
}
if !o.IsSorted {
o.sort()
}
o.Items = o.Items[:len(o.Items)-1]
return nil
}
func (o *Operation) removeMin() error {
if len(o.Items) == 0 {
return errors.New("empty items")
}
if !o.IsSorted {
o.sort()
}
o.Items = o.Items[1:]
return nil
}
func (o *Operation) sort() error {
if len(o.Items) == 0 {
return errors.New("empty items")
}
sort.Slice(o.Items, func(i, j int) bool {
return o.Items[i] < o.Items[j]
})
o.IsSorted = true
return nil
}
func solution(operations []string) []int {
var result = Operation{}
for _, operation := range operations {
commands := strings.Fields(operation)
switch commands[0] {
case InsertOperation:
result.push(commands[1])
default:
if commands[1] == RemoveMax {
result.removeMax()
} else {
result.removeMin()
}
}
}
return []int{result.Max(), result.Min()}
}

반응형