Skip to content

Instantly share code, notes, and snippets.

@terracotta-ko
Last active September 28, 2021 01:51
leetcode 503
class Solution {
fun nextGreaterElements(nums: IntArray): IntArray {
val longerNums = IntArray(nums.size*2)
for(i in nums.indices) {
longerNums[i] = nums[i]
longerNums[nums.size+i] = nums[i]
}
val nextGreatNumber = IntArray(longerNums.size)
val stack = mutableListOf<Int>()
for(i in longerNums.lastIndex downTo 0) {
while(stack.isNotEmpty() && longerNums[i] >= stack.last()) {
stack.removeAt(stack.lastIndex)
}
nextGreatNumber[i] = if(stack.isEmpty()) -1 else stack.last()
stack.add(longerNums[i])
}
return nextGreatNumber.take(nums.size).toIntArray()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment