[leetcode #496] Next Greater Element I

Seongyeol Shin·2021년 10월 19일
0

leetcode

목록 보기
54/196
post-thumbnail

Problem

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 1:

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.

Example 2:

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

Constraints:

・ 1 <= nums1.length <= nums2.length <= 1000
・ 0 <= nums1[i], nums2[i] <= 10⁴
・ All integers in nums1 and nums2 are unique.
・ All the integers of nums1 also appear in nums2.

Follow up: Could you find an O(nums1.length + nums2.length) solution?

Idea

난이도가 쉽고, O(nums1.length+nums2.length)로 풀어보라고 해서 처음부터 time complexity를 최소화하면서 풀려고 했다.

결론적으로는 O(nums1.length+nums2.length)으로 풀지는 못 했지만 결과는 이상하게 좋았다.

nums1에 있는 값들이 nums2의 어떤 위치에 있는지 확인하기 위해 indexDp를 만들었다. 그리고 next greater element의 유무를 확인하기 위해 maxDp를 만들어 해당 index 오른쪽에 있는 값 중 최대값을 저장하는 maxDp도 추가했다.

우선 nums2를 역순으로 탐색하면서 indexDp와 maxDp를 채웠다.

nums1을 탐색하면서 res에 next greater element를 채우게 된다. nums1의 수가 nums2의 오른쪽 끝이거나 maxDp를 참조해 오른쪽에 더 큰 값이 없을 경우 -1을 채운다. next greater element가 있다고 판단되면 해당 index의 오른쪽에 nums1의 수보다 큰 값이 등장하면 res array에 해당값을 채우고 다음 nums1을 탐색한다.

nums1의 탐색이 끝나면 값이 채워진 array를 리턴한다.

Solution

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] indexDp = new int[10_001];
        int[] maxDp = new int[nums2.length];
        int[] res = new int[nums1.length];

        Arrays.fill(indexDp, -1);
        for (int i=nums2.length-1; i >= 0; i--) {
            indexDp[nums2[i]] = i;
            if (i < nums2.length-1)
                maxDp[i] = Math.max(nums2[i], maxDp[i+1]);
            else
                maxDp[i] = nums2[i];
        }

        for (int i=0; i < nums1.length; i++) {
            int num = nums1[i];
            int index = indexDp[num];
            if (index == nums2.length -1 || maxDp[index+1] < num)
                res[i] = -1;
            for (int j=index+1; j < nums2.length; j++) {
                if (nums2[j] > num) {
                    res[i] = nums2[j];
                    break;
                }
            }
        }

        return res;
    }
}

Reference

https://leetcode.com/problems/next-greater-element-i/

profile
서버개발자 토모입니다

0개의 댓글