current position:Home>496 next element larger JavaScript implementation leetcode

496 next element larger JavaScript implementation leetcode

2022-04-29 04:27:52@huihui_ new

/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */
var nextGreaterElement = function(nums1, nums2) {
    
	//  Create an empty array 
    let stack = []
    //  Traversal array 1
    for(let i = 0; i < nums1.length; i++) {
    
        //  Judge in array 2 Which bit of the index , Is the last one to skip 
        if(!(nums2.indexOf(nums1[i]) === nums2.length - 1)) {
    
        	//  Not the last , Traverse the following array elements 
            for(let j = nums2.indexOf(nums1[i]) + 1;j < nums2.length; j++) {
    
            	//  There are elements larger than   Push straight in stack Array   The end of the cycle 
                if(nums2[j] > nums1[i]) {
    
                    stack.push(nums2[j])
                    break
                } 
                //  Traverse to the last bit   Still less than  -1 push stack
                if(nums2[j] < nums1[i] && nums2.indexOf(nums2[j]) === nums2.length - 1) {
    
                    stack.push(-1)
                }
            }
        } else {
    
            stack.push(-1)
        }
    }
    return stack
};

copyright notice
author[@huihui_ new],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270551339569.html

Random recommended