496. Next Greater Element I

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.

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.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

 

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

 

Note:

  1. All elements in nums1 and nums2 are unique.
  2. The length of both nums1 and nums2 would not exceed 1000.
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        int[] res = new int[n1];
        Arrays.fill(res, -1);
        // List<Integer> list1 = new ArrayList();
        // for(int i = 0; i < n1; i++) list1.
        
        for(int i = 0; i < n1; i++){
            int t = nums1[i];
            int j = 0;
            while(nums2[j] != t) j++;
            j++;
            for(; j < n2; j++){
                if(nums2[j] > t){
                   res[i] = nums2[j];
                    break;
                } 
            }
        }
        return res;
    }
}

什么狗jb描述,next greater number是说,nums1的element在nums2找到后,往右找有没有比它更大的,没有就是-1

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap();
        Stack<Integer> stack = new Stack();
        
        for(int i: nums2){
            while(!stack.isEmpty() && stack.peek() < i){
                map.put(stack.pop(), i);
            }
            stack.push(i);
        }
        for(int i = 0; i < nums1.length; i++){
            nums1[i] = map.getOrDefault(nums1[i], -1);
        }
        return nums1;
    }
}

2. O(n)

问的实际上是nums2的next greater number,用stack维持一个decrease的数们,如果当前比peek大,那就pop所有比peek小的,他们的ngn就是当前

用map存放每个数对应的ngn。

https://leetcode.com/problems/next-greater-element-i/discuss/97595/Java-10-lines-linear-time-complexity-O(n)-with-explanation

posted @ 2020-06-24 22:21  Schwifty  阅读(129)  评论(0编辑  收藏  举报