face Test 20: Print the Matrix clockwise
Train of thought: a lap to print, and then specific to four sides printed separately.
Java implementation of the subject:
public class Printmatrixincircle {public void printmatrixclockwisely (int[][] a) {if (a==null) return;
int rows=a.length;
int columns=a[0].length; int start=0;//starting position coordinates (0,0), (1,1) This while (Rows > start*2 && columns > start*2) {PRINTM
Atrixincircle (A,rows,columns,start);//print a circle of start++ from the start position; } private void Printmatrixincircle (int[][] A, int rows, int columns, int start) {int Endx=columns-start
-1;//the last column of this circle the subscript int endy=rows-start-1;//The last line of this lap for (int i = start; I <= endx; i++) {//print from left to right starting line
System.out.println (A[start][i]); } if (Start < EndY) {//Print columns from top to bottom for (int i = start+1 I <=endY; i++) {System.ou
T.println (A[i][endx]); } if (Start < EndX && Start < EndY) {//Right-to-left print line for (int i = endX-1; I >=st Art i--) {System.out.println (A[endy][i]); } if (Start < EndX && Start < endY-1) {//from bottom to top print column for (int i = endY-1; I >= start+1;
i--) {System.out.println (A[i][start]);
}} public static void Main (string[] args) {int[][] a={{1, 2, 3, 4},
{5, 6, 7, 8}, {9,10,11,12}, {13,14,15,16}};
Printmatrixincircle t=new printmatrixincircle ();
T.printmatrixclockwisely (a);
}
}
face Test 21: Stacks containing min functions
Define the data structure of the stack, in which you implement a min function that can get the smallest element of the stack, in which the min,push,pop time complexity is O (1).
Idea: Use two stacks, one normal processing, and the other to save the minimum value. In the stack, if the value is smaller than the minimum stack top value, then enter, otherwise the minimum stack top value. Take min every time to get the minimum stack top.
Java implementation of the subject:
public class stackwithmin<t>{stack<t> Stack = new stack<> ();
stack<t> minstack = new stack<> ();
public void push (t) {Stack.push (t); if (Minstack.isempty () | |
(integer) t < (integer) Minstack.peek ()) {Minstack.push (t);
}else{Minstack.push (Minstack.peek ());
The public void Pop () {if (!stack.isempty () &&!minstack.isempty ()) {stack.pop ());
Minstack.pop ();
} public void min () {if (!minstack.isempty ()) {System.out.println (Minstack.peek ());
} public static void Main (string[] args) {stackwithmin<integer> test = new stackwithmin<integer> ();
Test.push (2);
Test.push (2);
Test.push (3);
Test.min ();//2 Test.push (1);
Test.min ();//1 Test.pop (); Test.min ();//2}}