金山云Java方向9.16笔试
第一题:用long也越界了好像,n也太大了。过了91%。
public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); while (in.hasNext()) { int n=in.nextInt(); if(n<0) { System.out.println(0); continue; } long[] nums=new long[n]; long pre=0; nums[0]=1; for(int i=1;i<n;i++) { nums[i]=nums[i-1]+pre; pre=nums[i-1]; } for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { System.out.print(nums[j]+" "); } for(int k=i-1;k>=0;k--) { System.out.print(nums[k]+" "); } System.out.println(); } } } }第二题:反序列化二叉树+最近公共祖先。两道原题的结合版。AC
public class Main { static class TreeNode{ public int val; public TreeNode left; public TreeNode right; public TreeNode(int val) { this.val=val; } } static TreeNode p=new TreeNode(-1); static TreeNode q=new TreeNode(-1); static int pVal; static int qVal; public static void main(String[] args) { Scanner in=new Scanner(System.in); while (in.hasNextLine()) { String id=in.nextLine(); if(id==null || id.equals("")) { System.out.println(-1); continue; } String[] ids = id.split(" "); LinkedList<Integer> queue=new LinkedList<>(); for(int i=0;i<ids.length;i++) { queue.offer(Integer.valueOf(ids[i])); } String virus=in.nextLine(); String[] viruses = virus.split(" "); pVal=Integer.valueOf(viruses[0]); qVal=Integer.valueOf(viruses[1]); TreeNode root=bulidTree(queue); TreeNode res=getRes(root); if(res==null) { System.out.println(-1); }else { System.out.println(res.val); } } } private static TreeNode getRes(TreeNode root) { if(root==null || root==p || root==q) return root; TreeNode left=getRes(root.left); TreeNode right=getRes(root.right); if(left==null) return right; if(right==null) return left; return root; } private static TreeNode bulidTree(LinkedList<Integer> queue) { int val=queue.poll(); if(val==-1) { return null; } TreeNode root=new TreeNode(val); if(pVal==root.val) { p=root; } if(qVal==root.val) { q=root; } root.left=bulidTree(queue); root.right=bulidTree(queue); return root; } }