1.用栈实现队列
/*
用两个栈来实现队列
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:37.5 MB, 在所有 Java 提交中击败了7.14%的用户
*/private Stack<Integer> s1 ;private Stack<Integer> s2 ;/** Initialize your data structure here. */publicMyQueue(){
s1 =newStack<>();
s2 =newStack<>();}/** Push element x to the back of queue. */publicvoidpush(int x){
s1.add(x);}/** Removes the element from in front of queue and returns that element. */publicintpop(){
if(s1.isEmpty()&&s2.isEmpty()){
return-1;}if(!s1.isEmpty()&&s2.isEmpty()){
while(!s1.isEmpty()){
s2.add(s1.pop());}}return s2.pop();}/** Get the front element. */publicintpeek(){
if(s1.isEmpty()&&s2.isEmpty()){
return-1;}if(!s1.isEmpty()&&s2.isEmpty()){
while(!s1.isEmpty()){
s2.add(s1.pop());}}return s2.peek();}/** Returns whether the queue is empty. */publicbooleanempty(){
if(s1.isEmpty()&&s2.isEmpty()){
returntrue;}else{
returnfalse;}}
2.用队列实现栈
/*
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:37.5 MB, 在所有 Java 提交中击败了7.41%的用户
*/classMyStack{
private Queue<Integer> q1;private Queue<Integer> q2;/**
* Initialize your data structure here.
*/publicMyStack(){
q1 =newLinkedList<>();
q2 =newLinkedList<>();}/**
* Push element x onto stack.
*/publicvoidpush(int x){
q1.add(x);}/**
* Removes the element on top of the stack and returns that element.
*/publicintpop(){
if(q1.isEmpty()&& q2.isEmpty()){
return-1;}int temp =0;if(!q1.isEmpty()){
while(!q1.isEmpty()){
temp = q1.remove();
q2.add(temp);}
q2.remove(temp);}else{
while(!q2.isEmpty()){
temp = q2.remove();
q1.add(temp);}
q1.remove(temp);}return temp;}/**
* Get the top element.
*/publicinttop(){
if(q1.isEmpty()&& q2.isEmpty()){
return-1;}int temp =0;if(!q1.isEmpty()){
while(!q1.isEmpty()){
temp = q1.remove();
q2.add(temp);}}else{
while(!q2.isEmpty()){
temp = q2.remove();
q1.add(temp);}}return temp;}/**
* Returns whether the stack is empty.
*/publicbooleanempty(){
if(q1.isEmpty()&& q2.isEmpty()){
returntrue;}else{
returnfalse;}}}
3.01 矩阵
/*
寻找最短路径,采用BFS来做,不过这个时间消耗是真的多
执行用时:49 ms, 在所有 Java 提交中击败了6.47%的用户
内存消耗:43.3 MB, 在所有 Java 提交中击败了100.00%的用户
*/classSolution{
publicint[][]updateMatrix(int[][] matrix){
int len = matrix.length, len2 = matrix[0].length;int[][] ans =newint[len][len2];for(int i =0;i<len;i++){
for(int j =0;j<len2; j++){
ans[i][j]=BFS(matrix,len,len2,i,j);}}return ans;}privateintBFS(int[][] matrix,int len,int len2,int i,int j){
int count=0;
Queue<Integer> queue =newLinkedList<>();
Set<Integer> visited =newHashSet<>();
queue.add(i*len2+j);while(!queue.isEmpty()){
int size = queue.size();for(int k=0;k<size;k++){
int temp = queue.remove();int a = temp/len2,b = temp%len2;if(visited.contains(temp))continue;else visited.add(temp);if(matrix[a][b]==0){
return count;}if(a-1>=0) queue.add((a-1)*len2+b);if(a+1<len) queue.add((a+1)*len2+b);if(b-1>=0) queue.add(a*len2+b-1);if(b+1<len2) queue.add(a*len2+b+1);}
count++;}return count;}}