496- next higher element Ⅰ

496- next higher element Ⅰ

Given two no duplicate elements of the array nums1and nums2which nums1are nums2a subset. Find nums1each element in the nums2case of a value greater than that.

nums1The next higher element refers to the number x is x in nums2the first large element ratio x of the right side in the corresponding position. If not, the position output corresponding to -1.

Example 1:

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

Example 2:

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

note:

  1. nums1And nums2all elements are unique.
  2. nums1And nums2the array size is not more than 1,000.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/next-greater-element-i
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        int i;
        for (int j = 0; j < nums1.length; j++) {
            boolean flag = false;
            for (i = 0; i < nums2.length; i++) {
                if (nums2[i] == nums1[j]) {
                    flag = true;
                }
                if (flag && nums2[i] > nums1[j]) {
                    res[j] = nums2[i];
                    break;
                }
            }
            if(flag && i == nums2.length) {
                res[j] = -1;
            }
        }
        return res;
    }
    
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // 单调栈
        Stack<Integer> stack = new Stack<>();
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int value : nums2) {
            while (!stack.empty() && value > stack.peek()) {
                map.put(stack.pop(), value);
            }
            stack.push(value);
        }

        int[] res = new int[nums1.length];
        while (!stack.empty()) {
            map.put(stack.pop(), -1);
        }
        for (int j = 0; j < nums1.length; j++) {
            res[j] = map.get(nums1[j]);
        }
        return res;
    }

Guess you like

Origin www.cnblogs.com/angelica-duhurica/p/12227212.html