[코테 풀이] Next Greater Element I

시내·2024년 7월 15일

Q_1403) Next Greater Element I

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

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.

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        List<Integer> sample = new ArrayList<>();
        int that = 0;
        int z = 0;
        for (int n : nums2) sample.add(n);
        for (int a : nums1) {
            int index = sample.indexOf(a);
            for (int i = index; i < sample.size(); i++) {
                if (sample.get(i) > a) {
                    that = sample.get(i);
                    break;
                }
                else that = -1;
            }
            res[z++] = that;
        }
        return res;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글