496 下一个更大元素 I 简单
发布者:admin 发表于:417天前 阅读数:549 评论:0

496. 下一个更大元素 I 简单

给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。

请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

示例 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
    对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。
    对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。
    对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。

示例 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
    对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。
    对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。

提示:

1 <= nums1.length <= nums2.length <= 1000

0 <= nums1[i], nums2[i] <= 104

nums1和nums2中所有整数 互不相同

nums1 中的所有整数同样出现在 nums2 中

进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?

代码参考:

package main

import "fmt"

func main() {
    fmt.Println(nextGreaterElement([]int{4, 1, 2}, []int{1, 3, 4, 2}))     // [-1 3 -1]
    fmt.Println(bestNextGreaterElement([]int{4, 1, 2}, []int{1, 3, 4, 2})) // [-1 3 -1]
}

// 使用递减顺序栈,很 ok
func bestNextGreaterElement(findNums []int, nums []int) []int {
    m := make(map[int]int)
    var s Stack // 递减序列栈
    for _, num := range nums {
        for !s.IsEmpty() && s.Peek() < num { // 将 nums 中的数依次进栈,一直向下找比栈顶值还大的数
            m[s.Pop()] = num // 向上最接近的数
        }
        s.Push(num)
    }

    for i, num := range findNums {
        if greater, ok := m[num]; ok {
            findNums[i] = greater
        } else {
            findNums[i] = -1
        }
    }
    return findNums
}

// 干脆直接的遍历
func nextGreaterElement(findNums []int, nums []int) []int {
    n := len(nums)
    res := make([]int, 0, len(findNums))
    for _, target := range findNums {
        for i, num := range nums {
            if num != target {
                continue
            }

            // 直接向后找第一个比 target 大的数
            found := false
            for j := i + 1; j < n; j++ {
                if nums[j] > target {
                    found = true
                    res = append(res, nums[j])
                    break
                }
            }
            if !found {
                res = append(res, -1)
            }
        }
    }
    return res
}