[Problem] Next Greater Element I

댕청·2025년 6월 30일

문제 풀이

목록 보기
14/38

Problem Statement

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

Example

Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.

Approach

We build a map (hashmap) that stores the next greater element for every number in nums2.

If an element in nums2 has no next greater element, its value in the map is -1.

Finally, for each number in nums1 (which is guaranteed to be in nums2), we look up its next greater element directly from the map.

So the returned list has the next greater elements for all nums1 elements in order.

Solution

class Solution:
    def nextGreaterElement(self, nums1, nums2):
        stack = []
        hashmap = {}

        for num in nums2:
            while stack and num > stack[-1]:
                hashmap[stack.pop()] = num
            stack.append(num)

        result = []
        for i in nums1:
            result.append(hashmap.get(i, -1))
        return result
profile
될때까지 모든 걸 다시 한번

0개의 댓글