import java.util.Queue
import java.util.LinkedList
class Solution {
fun solution(priorities: IntArray, location: Int): Int {
val prio : Queue<Int> = LinkedList<Int>()
priorities.forEach{prio.add(it)}
var answer:Int = 0
var fun_location : Int = location
var size = priorities.size
while (true){
var max : Int? = prio.max()
var pop_num : Int = prio.remove()
if(pop_num == max) {
--size
answer++
if(fun_location == 0) return answer
fun_location -= 1
}else{
prio.add(pop_num)
fun_location -= 1
}
if(fun_location < 0) fun_location = size + fun_location
}
}
}
풀기는 했는데 사실상 전혀 코틀린 스타일 코드가 아니다.
다른 사람들이 푼걸 좀 찾아봐야지
똑같이 linkedlist를 사용했는데 그냥 index와 value를 넣어버리고 인덱스를 사용하는게 아니라
저 리스트 자체를 이용해버리면 되는구나.
import java.util.*
data class Doc(val p: Int, val i: Int)
fun solution(priorities: IntArray, location: Int): Int {
val list: LinkedList<Doc> = LinkedList<Doc>()
priorities
.forEachIndexed { index, value ->
list.add(Doc(value, index))
}
var answer: Int = 0
while (true) {
val now = list.poll()
if (list.any { now.p < it.p }) {
list.add(now)
} else {
answer++
if (now.i == location)
break
}
}
return answer
}
linkedlist를 사용하지 않은 사람의 풀이
이게 조금 더 코틀린에 맞지 않나 싶다.
when문은 맨 위에꺼가 만족하면 그냥 끝나버리는구나.
when {
x == 3 -> println("x is odd")
y == 4 -> println("y is even")
else -> println("x+y is even.")
}
여기서 x = 3, y = 4 이거라고해도 x = 3만 실행되고 끝난다.
class Solution {
fun solution(priorities: IntArray, location: Int): Int {
var answer = 1
var arr = priorities.mapIndexed { index, value ->
Pair(value, index == location) // index랑 location 같으면 true 아니면 false
}
loop@ while (arr.isNotEmpty()) {
val tmp = arr[0]
val otherArr = arr.subList(1, arr.size)
arr = when {
otherArr.any { it.first > tmp.first } -> otherArr + tmp // 제일큰거 아니면 뒤에 더해
tmp.second -> break@loop // temp // 1번 when이 실행 안되었다는건 이게 제일 크다는 말
// 근데 그게 true 즉 location 이다? 그럼 끝내
else -> { // 제일 큰데 location 아님 그럼 answer ++ 해주고 arr = otherArr
answer++
otherArr
}
}
}
return answer
}
}
댓글 영역