Another easy to understand solution for an easy-level LC problem.
class Solution {
fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
var output = IntArray(nums1.size)
nums1.forEachIndexed {index, num1 ->
var location = nums2.indexOfFirst { it == num1}
if(location != -1){
var greater = nums2.sliceArray(location+1 until nums2.size).firstOrNull { it > num1 }
if(greater != null) output[index] = greater else output[index] = -1
}else output[index] = -1
}
return output
}
}
Runtime: 220 ms, faster than 31.25% of Kotlin online submissions for Next Greater Element I.
Memory Usage: 37.3 MB, less than 100.00% of Kotlin online submissions for Next Greater Element I.
We iterate nums1 and for each element, we try to find it’s index in nums2. Then we’ll use this location to slice the array to reduce the search space and find the next greater element.