1. 程式人生 > >[Swift Weekly Contest 130]LeetCode1019. 鏈表中的下一個更大節點 | Next Greater Node In Linked List

[Swift Weekly Contest 130]LeetCode1019. 鏈表中的下一個更大節點 | Next Greater Node In Linked List

return 給定 1-1 rom 第一個 node color gre hat

We are given a linked list with head as the first node. Let‘s number the nodes in the list: node_1, node_2, node_3, ... etc.

Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j

does not exist, the next larger value is 0.

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

Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and 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] 

Note:

  1. 1 <= node.val <= 10^9 for each node in the linked list.
  2. The given list has length in the range [0, 10000].

給出一個以頭節點 head

作為第一個節點的鏈表。鏈表中的節點分別編號為:node_1, node_2, node_3, ...

每個節點都可能有下一個更大值(next larger value):對於 node_i,如果其 next_larger(node_i)node_j.val,那麽就有 j > inode_j.val > node_i.val,而 j 是可能的選項中最小的那個。如果不存在這樣的 j,那麽下一個更大值為 0

返回整數答案數組 answer,其中 answer[i] = next_larger(node_{i+1})

註意:在下面的示例中,諸如 [2,1,5] 這樣的輸入(不是輸出)是鏈表的序列化表示,其頭節點的值為 2,第二個節點值為 1,第三個節點值為 5 。

示例 1:

輸入:[2,1,5]
輸出:[5,5,0]

示例 2:

輸入:[2,7,4,3,5]
輸出:[7,0,5,5,0]

示例 3:

輸入:[1,7,5,1,9,2,5,1]
輸出:[7,9,9,9,0,5,0,0] 

提示:

  1. 對於鏈表中的每個節點,1 <= node.val <= 10^9
  2. 給定列表的長度在 [0, 10000] 範圍內

Runtime: 764 ms Memory Usage: 21.5 MB
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public var val: Int
 5  *     public var next: ListNode?
 6  *     public init(_ val: Int) {
 7  *         self.val = val
 8  *         self.next = nil
 9  *     }
10  * }
11  */
12 class Solution {
13     var ret:[Int] = [Int]()
14     var d:[(Int,Int)] = [(Int,Int)]()
15     var ans:[Int] = [Int]()
16     
17     func nextLargerNodes(_ head: ListNode?) -> [Int] {
18         var head = head
19         while(head != nil)
20         {
21             ret.append(head!.val)
22             head = head?.next
23         }
24         for i in stride(from:ret.count - 1,through:0,by:-1)
25         {
26             while(d.count != 0 && d.first!.0 <= ret[i])
27             {
28                 
29                 d.removeFirst()                
30             }
31             if d.count != 0
32             {
33                 ans.append(d.first!.0)
34             }
35             else
36             {
37                 ans.append(0)
38             }
39             d.insert((ret[i],i),at:0)
40         }
41         return ans.reversed()
42     }
43 }

[Swift Weekly Contest 130]LeetCode1019. 鏈表中的下一個更大節點 | Next Greater Node In Linked List