第二十一题
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
ArrayList<Integer> A=new ArrayList<>();
ArrayList<Integer> B=new ArrayList<>();
Stack<Integer> s=new Stack<>();
for (int a : pushA) {
A.add(a);
}
for (int b : popA) {
B.add(b);
}
//弹出序列的第一个元素被弹出时,入栈序列中该元素之前的元素都已入栈
//没将弹出的元素入栈,假设是入栈后又立即出栈
if(!A.contains(B.get(0))) return false;
for(int i=0;i<A.indexOf(B.get(0));i++) {
s.push(A.get(i));
}
for(int i=1;i<popA.length;i++) {
if(!A.contains(B.get(i))) return false;
if(A.indexOf(B.get(i))>A.indexOf(B.get(i-1))) {
for(int j=A.indexOf(B.get(i-1))+1;j<A.indexOf(B.get(i));j++) {
s.push(A.get(j));
}
}else if(!s.pop().equals(B.get(i))) return false;
}
return true;
}
}
运行时间:11ms
占用内存:9048k
第二十五题
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
import java.util.ArrayList;
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null) return null;
RandomListNode N=pHead;
ArrayList<RandomListNode> array=new ArrayList<>();
while(pHead!=null) {
RandomListNode node=new RandomListNode(pHead.label);
array.add(node);
pHead=pHead.next;
}
for(int j=0;j<array.size()-1;j++) {
array.get(j).next =array.get(j+1);
}
array.get(array.size()-1).next=null;
for(int i=0;i<array.size();i++) {
if(N.random!=null) {
int j;
for(j=0;j<array.size();j++) {
if(array.get(j).label==N.random.label) break;
}
array.get(i).random=array.get(j);
}else array.get(i).random=null;
N=N.next;
}
return array.get(0);
}
}
运行时间:17ms
占用内存:9668k