4.27腾讯音乐笔试题解
记录下 实习0 offer的本菜逼的第一次笔试ak
今晚笔试这么水来看 估计是没有hc了😭
贴下自己写的代码:
第一题 其实不用想那么复杂 层序遍历直接莽
ArrayList<TreeNode> res = new ArrayList<>(); public ArrayList<TreeNode> deleteLevel (TreeNode root, ArrayList<Integer> a) { // write code here Queue<TreeNode> que = new LinkedList<>(); if(root != null) que.offer(root); int depth = 1; if( !a.contains(1)) res.add(root); while(!que.isEmpty()){ int size = que.size(); for(int i=0;i<size;i++){ TreeNode tmp = que.poll(); if(tmp.left != null) que.offer(tmp.left); if(tmp.right != null) que.offer(tmp.right); if(a.contains(depth+1)){ //如果此层是要删除的上一层 tmp.left = null; tmp.right = null; //就斩断联系 } else if(a.contains(depth)){ //如果此层就是要删除的那层 if(tmp.left !=null){ res.add(tmp.left); tmp.left = null; } if(tmp.right !=null){ res.add(tmp.right); tmp.right = null; } } } depth++; } return res; }第二题 我是用个哈希表先存储下 结点的val 和 结点地址 的对应关系,然后把树结点val全部清空,在val上做异或运算
public TreeNode xorTree (TreeNode root, ArrayList<ArrayList<Integer>> op) { // write code here Map<Integer,TreeNode> table = new HashMap<>(); Queue<TreeNode> que = new LinkedList<>(); if(root !=null) que.add(root); int num=0; while(!que.isEmpty()){ TreeNode tmp = que.poll(); num++; table.put(tmp.val,tmp); tmp.val = 0; if(tmp.left !=null) que.offer(tmp.left); if(tmp.right !=null) que.offer(tmp.right); } for(int i=0;i<op.size();i++){ List<Integer> tmp = op.get(i); int index = tmp.get(0); int nums = tmp.get(1); TreeNode node = table.get(index) helper(node,nums); } return root; } public void helper(TreeNode root,int num){ if(root ==null) return; root.val = root.val ^ num; if(root.left!=null) helper(root.left,num); if(root.right !=null) helper(root.right,num); }第三题 ···有手就行
int res=0; public int howMany (String S, int k) { // write code here Map<Character,Integer> table = new HashMap<>(); for(int i=0;i< S.length();i++){ int times = table.getOrDefault(S.charAt(i),0); if(times == k-1){ res++; } if(times < k ){ table.put(S.charAt(i),times+1); } } return res; }