本文最后编辑于 前,其中的内容可能需要更新。
496.下一个更大元素I
给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。
请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。
示例 1:
1 2 3 4 5 6
| 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。 对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。 对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
|
示例 2:
1 2 3 4 5
| 输入: nums1 = [2,4], nums2 = [1,2,3,4]. 输出: [3,-1] 解释: 对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。 对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
|
提示:
- 1 <= nums1.length <= nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 104
- nums1和nums2中所有整数 互不相同
- nums1 中的所有整数同样出现在 nums2 中
原文链接
解题思路
1.暴力解法
遍历nums1,每次都在nums2中找到对应元素,寻找到后面一个更大的元素,填入数组中,没有就填-1
2.栈和Map
将nums2的元素依次入栈,如果小于栈顶元素则入栈,如果大于栈顶则出栈,并写道map当中。最后遍历一次nums1从map中寻找对应的值,如果没有则是-1即可
解题代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { int[] result = new int[nums1.length]; for (int i = 0;i < nums1.length;i++){ int max = -1; boolean flag = false; for (int j = 0;j < nums2.length;j++){ if (nums1[i] == nums2[j]) flag = true; if (nums2[j] > nums1[i] && flag){ max = nums2[j]; break; } } result[i] = max; } return result; } public int[] nextGreaterElement2(int[] nums1, int[] nums2){ int[] result = new int[nums1.length]; Map<Integer, Integer> map = new HashMap<>(); Stack<Integer> stack = new Stack<>(); for (int num : nums2){ while(!stack.isEmpty() && stack.peek() < num){ map.put(stack.pop(),num); } stack.push(num); } for (int i = 0;i < nums1.length;i++){ result[i] = map.getOrDefault(nums1[i],-1); } return result; } }
|