第一题,
实现一个最大栈和最小栈
有pop操作
有push操作
有获取最大栈方法
有获取最小栈方法
static Stack<Integer> s1=new Stack<>();
static Stack<Integer> s2=new Stack<>();
static Stack<Integer> sMin=new Stack<>();
static Stack<Integer> sMax=new Stack<>();
public static void pop(){
if(sMin.peek().equals(s1.peek())){
sMin.pop();
}if(sMax.peek().equals(s2.peek())){
sMax.pop();
}
s1.pop();
s2.pop();
}
public static void push(int x){
s1.push(x);
s2.push(x);
if(sMin.isEmpty()||sMin.peek()>=x)sMin.push(x);
if(sMax.isEmpty()||sMax.peek()<=x)sMax.push(x);
}
public static int getMin(){
return sMin.peek();
}
public static int getMax(){
return sMax.peek();
}
第二题:
实现迪杰斯特拉算法,求任意一节点到其他节点的最短路径:
public static void Di(int [][]weight,int start){
int length=weight.length;
int [] shortPath=new int[length];
shortPath[0]=0;
String path[]=new String[length];
for(int i=0;i<length;i++){
path[i]= start+"->"+i;
}
int visited[]=new int[length];
visited[0]=1;
for(int count =1;count<length;count++){
int k=-1;
int dmin=Integer.MAX_VALUE;
for(int i=0;i<length;i++){
if(visited[i]==0&&weight[start][i]<dmin){
dmin= weight[start][i];
k=i;
}
}
shortPath[k]=dmin;
visited[k]=1;
for(int i=0;i<length;i++){
if(visited[i]==0&& weight[k][i] != Integer.MAX_VALUE&&weight[start][k]+weight[k][i]<weight[start][i]){
weight[start][i]=weight[start][k]+weight[k][i];
path[i]=path[k]+"->"+i;
}
}
}
for(int i=0;i<length;i++){
System.out.println("从 "+start+"出发到 "+i+"的最短路径 "+path[i]+"值为:"+shortPath[i]+",");
}
//return shortPath;
}
测试用例:
6 0
-1 1 4 -1 -1 -1
1 -1 2 7 5 -1
4 2 -1 -1 1 -1
-1 7 -1 -1 3 2
-1 5 1 3 -1 6
-1 -1 -1 2 6 -1
第一行第一个数字
代表n*n的邻接矩阵
第一行第二个数字代表起始点
接下来是邻接矩阵。