leetcode 1019 the list of the next higher node

Head to head node is given as a list of the first node. The list of the nodes are numbered: node_1, node_2, node_3, ....

Each node may have a greater value of the next (next larger value): For node_i, if it next_larger (node_i) is node_j.val, then there j> i and node_j.val> node_i.val, and j is possible the smallest of the options. If such a j does not exist, the next larger value of 0.

Returns an array of integers answer answer, where answer [i] = next_larger (node_ {i + 1}).

Note: In the following example, such as [2,1,5] Such an input (not output) the sequence of the list represents a value of 2, the second node is a head node thereof, the third node value of 5.

 

Example 1:

Input: [2,1,5]
Output: [5,5,0]
Example 2:

Input: [2,7,4,3,5]
Output: [7,0,5,5,0]
Example 3:

Input: [1,7,5,1,9,2,5,1]
Output: [7,9,9,9,0,5,0,0]
 

prompt:

For each node in the linked list, 1 <= node.val <= 10 ^ 9
the length of the list given in [0, 10000] in the range of

Ideas: originally wrote a version of the recursive method, processing time backtracking. But must save a queue and then transferred to turn to become int []. Very troublesome.

Comments, using a monotonic stack.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] nextLargerNodes(ListNode head) {
       ArrayList<Integer> A = new ArrayList<>();
        for (ListNode node = head; node != null; node = node.next)
            A.add(node.val);
        int[] res = new int[A.size()];
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < A.size(); ++i) {
            while (!stack.isEmpty() && A.get(stack.peek()) < A.get(i))
                res[stack.pop()] = A.get(i);
            stack.push(i);
        }
        return res;
        
    }

}

 

Published 315 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_39137699/article/details/104105543