关于java:LeetCode496下一个更大元素-I

6次阅读

共计 1164 个字符,预计需要花费 3 分钟才能阅读完成。

下一个更大元素 I

题目形容:给你两个 没有反复元素 的数组 nums1 和 nums2,其中 nums1 是 nums2 的子集。

请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应地位的左边的第一个比 x 大的元素。如果不存在,对应地位输入 -1。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:暴力破解法

首先,申明一个大小和 nums 一样的数组用来寄存后果,而后遍历 nums1 中的元素:

  • 申明 2 个 boolean 变量,equals 示意是否找到 nums2 中于以后 nums 地位的值相等的元素;
  • found 示意是否找到在 nums2 中对应地位的左边的第一个比 x 大的元素;
  • 内层循环遍历 nums2 中的元素,找到和 nums1 以后地位雷同的元素,而后判断其前面是否存在比之更大的元素,如果没有找到,将后果集中相应地位的元素置为 -1。

最初,返回后果集。

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 + ",");
        }
    }
}

【每日寄语】 舍弃无限,博得有限。

正文完
 0