暴力破解与最直观的写法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
vector<int> list;
while(head)
{
list.push_back(head->val);
head = head->next;
}
int size = list.size();
for(int i = 0,j = 0;i < size;i++)
{
bool flag = false;
for(j = i + 1;j < size;j++)
{
if(list[j] > list[i])
{
list[i] = list[j];
flag = true;
break;
}
}
if(j == size && flag == false)
list[i] = 0;
}
list[size - 1] = 0;
return list;
}
};
毫无意外的执行结果超时:
Time Limit Exceeded
Details
Last executed input
[10000,10000,10000,10000,10000,10000,9999,9998,9998,9996,9994,9992,9992,9990,9990,9989,……]
优化后的代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
vector<int> res,stack;
while(head)
{
res.push_back(head->val);
head = head->next;
}
for(int i = res.size() - 1;i >= 0;i--)
{
auto val = res[i];
while(!stack.empty() && val >= stack.back()) stack.pop_back();
res[i] = stack.empty() ? 0:stack.back();
stack.push_back(val);
}
return res;
}
};
这里从后往前处理,初始时stack为空,res最后元素为0,然后将修改前的val存入stack,后面判断stack只要非空,判断当前值只要不比stack里的元素小,就讲元素弹出,这样就保留了最新的最大值。
程序执行结果:
Runtime: 144 ms, faster than 40.57% of C++ online submissions for Next Greater Node In Linked List.
Memory Usage: 41.8 MB, less than 57.03% of C++ online submissions for Next Greater Node In Linked List.