【发布时间】:2019-08-17 10:07:50
【问题描述】:
我用蛮力的方式回答了这个问题。我使用了两个循环,时间效率很差。这是代码:-
public int[] nextLargerNodes(ListNode head) {
int len = 0;
ListNode temp = head;
while(temp != null) {
len++;
temp = temp.next;
}
int[] answer = new int[len];
temp = head;
int i = 0;
while(temp.next != null) {
ListNode nextGreat = temp.next;
while(nextGreat != null) {
if(nextGreat.val > temp.val) {
answer[i] = nextGreat.val;
i++;
break;
}
else {
nextGreat = nextGreat.next;
}
}
if(nextGreat == null) {
answer[i++] = 0;
}
temp = temp.next;
}
answer[i] = 0;
return answer;
}
然后我找到了另一种使用堆栈来解决问题的解决方案,但是该解决方案也使用了两个循环。第二种解决方案的效率要好得多,即使它不是 O(n),因为它有两个循环。代码:-
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;
}
我想知道是什么让堆栈解决方案与蛮力方式相比效率更高,尽管这两种解决方案都有两个循环。
【问题讨论】:
-
第二种解决方案也有问题;我们需要从列表中推入第 i 个元素,而不是将 i 的值推入堆栈,例如 --stack.push(A.get(i));
标签: java data-structures stack