|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.Map; |
| 4 | +import java.util.Stack; |
| 5 | + |
| 6 | +/** |
| 7 | + * You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. |
| 8 | + * The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. |
| 9 | + * <p> |
| 10 | + * Example 1: |
| 11 | + * Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. |
| 12 | + * Output: [-1,3,-1] |
| 13 | + * Explanation: |
| 14 | + * For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. |
| 15 | + * For number 1 in the first array, the next greater number for it in the second array is 3. |
| 16 | + * For number 2 in the first array, there is no next greater number for it in the second array, so output -1. |
| 17 | + * <p> |
| 18 | + * Example 2: |
| 19 | + * Input: nums1 = [2,4], nums2 = [1,2,3,4]. |
| 20 | + * Output: [3,-1] |
| 21 | + * Explanation: |
| 22 | + * For number 2 in the first array, the next greater number for it in the second array is 3. |
| 23 | + * For number 4 in the first array, there is no next greater number for it in the second array, so output -1. |
| 24 | + * <p> |
| 25 | + * Note: |
| 26 | + * All elements in nums1 and nums2 are unique. |
| 27 | + * The length of both nums1 and nums2 would not exceed 1000. |
| 28 | + * <p> |
| 29 | + * Created by drfish on 6/14/2017. |
| 30 | + */ |
| 31 | +public class _496NextGreaterElementI { |
| 32 | + public int[] nextGreaterElement(int[] findNums, int[] nums) { |
| 33 | + Map<Integer, Integer> map = new HashMap<>(); |
| 34 | + Stack<Integer> stack = new Stack<>(); |
| 35 | + |
| 36 | + for (int num : nums) { |
| 37 | + while (!stack.isEmpty() && num > stack.peek()) { |
| 38 | + map.put(stack.pop(), num); |
| 39 | + } |
| 40 | + stack.push(num); |
| 41 | + } |
| 42 | + |
| 43 | + int[] result = new int[findNums.length]; |
| 44 | + for (int i = 0; i < findNums.length; i++) { |
| 45 | + result[i] = map.getOrDefault(findNums[i], -1); |
| 46 | + } |
| 47 | + return result; |
| 48 | + } |
| 49 | + |
| 50 | + public static void main(String[] args) { |
| 51 | + _496NextGreaterElementI solution = new _496NextGreaterElementI(); |
| 52 | + assert Arrays.equals(new int[]{-1, 3, -1}, solution.nextGreaterElement(new int[]{4, 1, 2}, new int[]{1, 3, 4, 2})); |
| 53 | + assert Arrays.equals(new int[]{3, -1}, solution.nextGreaterElement(new int[]{2, 4}, new int[]{1, 2, 3, 4})); |
| 54 | + } |
| 55 | +} |
0 commit comments