1
头图

next larger element I

Problem Description: You are given two arrays nums1 and nums2 without repeating elements, where nums1 is a subset of nums2.

Find the next larger value in nums2 for each element in nums1.

The next greater element of the number x in nums1 is the first element greater than x to the right of the corresponding position of x in nums2. If it does not exist, output -1 for the corresponding position.

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/next-greater-element-i/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: Brute-force cracking method

First, declare an array of the same size as nums to store the result, then iterate over the elements in nums1:

  • Declare 2 boolean variables, equals indicates whether the element in nums2 with the same value at the current nums position is found;
  • found indicates whether to find the first element larger than x to the right of the corresponding position in nums2;
  • The inner loop traverses the elements in nums2, finds the element with the same position as the current position of nums1, and then judges whether there is an element larger than that behind it. If not, set the element in the corresponding position in the result set to -1.

Finally, return the result set.

 public class LeetCode_496 {
    /**
     * 暴力破解法
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // 结果集
        int[] result = new int[nums1.length];
        // 遍历nums1中的元素
        for (int i = 0; i < nums1.length; i++) {
            // equals表示是否找到nums2中于当前nums位置的值相等的元素
            // found表示是否找到在 nums2 中对应位置的右边的第一个比 x 大的元素
            boolean equals = false, found = false;
            for (int j = 0; j < nums2.length; j++) {
                if (equals) {
                    if (nums2[j] > nums1[i]) {
                        found = true;
                        result[i] = nums2[j];
                        break;
                    }
                } else {
                    if (nums2[j] == nums1[i]) {
                        equals = true;
                    }
                }
            }
            // 最后,如果么找到,则将当前位置的值置为-1
            if (!found) {
                result[i] = -1;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] num1 = {4, 1, 2};
        int[] num2 = {1, 3, 4, 2};
        // 测试用例,期望输出: -1,3,-1
        for (int i : nextGreaterElement(num1, num2)) {
            System.out.print(i + ",");
        }
    }
}
[Daily Message] Give up the limited and win the unlimited.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!