贝壳笔试记录
1 题 在[0..n-1]上来回走,允许走m步,返回每个位置走过多少次。
import java.util.*; public class Solution { public static void main(String[] args) { long[] res = new Solution().FarmerNN(2, 5); System.out.println(Arrays.toString(res)); } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @param m long长整型 * @return long长整型一维数组 */ public long[] FarmerNN (int n, long m) { long[] ret = new long[n]; long base = m / (n - 1); ret[n-1] = base >> 1; ret[0] = (base >> 1) + (base & 1); Arrays.fill(ret, 1, n -1, base); int cur = 0, step = 1; if ((base & 1) == 1) { cur= n - 1; step = -1; } long left = m % (n - 1); while(left-- > 0) { ret[cur]++; cur += step; } return ret; } }2 题 按照题意写
public class Solution { public static void main(String[] args) { String res = new Solution().NS_String("aaaaa",1); System.out.println(res); } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param k int整型 * @return string字符串 */ public String NS_String (String s, int k) { boolean[] exist = new boolean[128]; for (int i = 0; i < s.length(); ++i) { exist[s.charAt(i)] = true; } char ch = 'a'; while(k > 0) { while(!exist[ch]) ++ch; exist[ch] = false; --k; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); ++i) { if (exist[s.charAt(i)]) { sb.append(s.charAt(i)); } } return sb.toString(); } }
3 题 有些难,不会做
4 题 树的序列化
但是StackOverflowError了,递归层次太深了。只能过90.91%
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ Set<String> set; int maxV; public int maxSubTree (TreeNode root) { if (root == null) return 0; set = new HashSet<>(); // 存放数的序列化 maxV = 0; travel(root); return maxV; } private String travel(TreeNode rt) { if (rt == null) { return "#"; } String leftString = travel(rt.left); String rightString = travel(rt.right); String ret = "1" + leftString + rightString; if (set.contains(ret)) { maxV = Math.max(maxV, onesCount(ret)); } else { set.add(ret); } return ret; } private int onesCount(String s) { int count = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == '1') { count++; } } return count; } }