题目
解法
遍历一遍 nums2
, 算出来每个元素的下一个最大元素,然后遍历 nums1
取结果
暴力解法:
class Solution {
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @return Integer[]
*/
function nextGreaterElement($nums1, $nums2) {
if (empty($nums2) || empty($nums1)) {
return [];
}
$pairRet = [];
$toPair = [];
foreach ($nums2 as $key => $n2) {
foreach ($toPair as $key => $item) {
if ($item < $n2) {
$pairRet[$item] = $n2;
unset($toPair[$key]);
}
}
$toPair[] = $n2;
}
$ret = [];
foreach ($nums1 as $item) {
$ret[] = $pairRet[$item] ?: -1;
}
return $ret;
}
}
单调栈
function nextGreaterElement($nums1, $nums2) {
if (empty($nums2) || empty($nums1)) {
return [];
}
$n2Ret = [];
$stack = [];
foreach ($nums2 as $key => $n2) {
if (empty($stack)) {
$stack[] = $n2;
} else {
// 维护一个栈,里面的值总是递减的单调栈
while (!empty($stack) && $stack[count($stack) - 1] < $n2) {
$n2Ret[array_pop($stack)] = $n2;
}
$stack[] = $n2;
}
}
$ret = [];
foreach ($nums1 as $item) {
$ret[] = $n2Ret[$item] ?: -1;
}
return $ret;
}