网易笔试9.12 Java后端岗
四道编程,两道问答,问答不难,阻塞队列;sleep和wait区别,都是经典面试题。
AC了两道,第三第四都没怎么来得及思考。太菜。附一下自己的Java代码,我感觉都是偏暴力的解法:
第一题 找樱桃节点
输入用例:第一行节点数+连接点的枝干数量
10 9
1 left 2
1 right 3
2 left 4
2 right 5
3 right 6
6 left 7
6 right 8
7 left 9
7 right 10
1 left 2
1 right 3
2 left 4
2 right 5
3 right 6
6 left 7
6 right 8
7 left 9
7 right 10
由于这个输入用例很奇怪,之前在leetcode没遇到过,所以卡了很久。后来用了一个二维数组(m+1)*2来保存节点的左右节点信息,因为根节点是1,所以我直接把0行给去了,之后读好读。
两个hashset分别存有子节点的父节点和叶子结点。
最后条件判断筛选父节点就好了。
public class Main {
public static void main(String[] args) {
int res =0;
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
//存左右节点信息
int[][] dict = new int[m+1][2];
String nullS = sc.nextLine();
HashSet<Integer> roots = new HashSet<>();
for(int i =0;i<n;i++){
String s = sc.nextLine();
String[] strs = s.split(" ");
roots.add(Integer.parseInt(strs[0]));
if(strs[1].equals("left")){
dict[Integer.parseInt(strs[0])][0] = Integer.parseInt(strs[2]);
}
if(strs[1].equals("right")){
dict[Integer.parseInt(strs[0])][1] = Integer.parseInt(strs[2]);
}
}
HashSet<Integer> leaf = new HashSet<>();
for(int i = 1;i<=m;i++){
for(int j =0;j<2;j++){
if(dict[i][j] != 0 && !roots.contains(dict[i][j])){
leaf.add(dict[i][j]);
}
}
}
for(int i = 1;i<=m;i++){
if(roots.contains(i) && leaf.contains(dict[i][0] )&& leaf.contains(dict[i][1])){
res++;
}
}
System.out.println(res);
}
} 第二题 最长子序列,条件是a,b,c,x,y,z出现了偶数次(包括0)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] chars = s.toCharArray();
int len = s.length();
boolean[][] dict = new boolean[len][len];
int maxLen = 0;
for(int i = 0; i<len; i++){
int a = 0, b =0, c =0,x =0,y=0,z=0;
int temp = i;
for(int j = i;j<len;j++) {
if (chars[j] == 'a') {
a++;
}
if (chars[j] == 'b') {
b++;
}
if (chars[j] == 'c') {
c++;
}
if (chars[j] == 'x') {
x++;
}
if (chars[j] == 'y') {
y++;
}
if (chars[j] == 'z') {
z++;
}
if (a % 2 == 0 && b % 2 == 0 && c % 2 == 0 && x % 2 == 0 && y % 2 == 0 && z % 2 == 0) {
dict[i][j] = true;
temp = j;
}
if (temp - i > 0) {
maxLen = Math.max(temp - i + 1, maxLen);
}
}
}
System.out.println(maxLen);
}
请大佬点评指正!
