完美世界2020暑期實習生春招Java後臺筆試題

第一題,

實現一個最大棧和最小棧

有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的鄰接矩陣

第一行第二個數字代表起始點

接下來是鄰接矩陣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章