前言

省略的代码:

  1. import java.util.*;
  1. public class Solution {
  2. }
  1. public class Main {
  2. public static void main(String[] args) {
  3. Scanner in = new Scanner(System.in);
  4. while (in.hasNext()) {
  5. }
  6. }
  7. }

1. 小米-小米Git

  • 重建多叉树
  • 使用 LCA
  1. private class TreeNode {
  2. int id;
  3. List<TreeNode> childs = new ArrayList<>();
  4. TreeNode(int id) {
  5. this.id = id;
  6. }
  7. }
  8. public int getSplitNode(String[] matrix, int indexA, int indexB) {
  9. int n = matrix.length;
  10. boolean[][] linked = new boolean[n][n]; // 重建邻接矩阵
  11. for (int i = 0; i < n; i++) {
  12. for (int j = 0; j < n; j++) {
  13. linked[i][j] = matrix[i].charAt(j) == '1';
  14. }
  15. }
  16. TreeNode tree = constructTree(linked, 0);
  17. TreeNode ancestor = LCA(tree, new TreeNode(indexA), new TreeNode(indexB));
  18. return ancestor.id;
  19. }
  20. private TreeNode constructTree(boolean[][] linked, int root) {
  21. TreeNode tree = new TreeNode(root);
  22. for (int i = 0; i < linked[root].length; i++) {
  23. if (linked[root][i]) {
  24. linked[i][root] = false; // 因为题目给的邻接矩阵是双向的,在这里需要把它转为单向的
  25. tree.childs.add(constructTree(links, i));
  26. }
  27. }
  28. return tree;
  29. }
  30. private TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
  31. if (root == null || root.id == p.id || root.id == q.id) return root;
  32. TreeNode ancestor = null;
  33. int cnt = 0;
  34. for (int i = 0; i < root.childs.size(); i++) {
  35. TreeNode tmp = LCA(root.childs.get(i), p, q);
  36. if (tmp != null) {
  37. ancestor = tmp;
  38. cnt++;
  39. }
  40. }
  41. return cnt == 2 ? root : ancestor;
  42. }

2. 小米-懂二进制

对两个数进行异或,结果的二进制表示为 1 的那一位就是两个数不同的位。

  1. public int countBitDiff(int m, int n) {
  2. return Integer.bitCount(m ^ n);
  3. }

3. 小米-中国牛市

背包问题,可以设一个大小为 2 的背包。

状态转移方程如下:

  1. dp[i, j] = max(dp[i, j-1], prices[j] - prices[jj] + dp[i-1, jj]) { jj in range of [0, j-1] } = max(dp[i, j-1], prices[j] + max(dp[i-1, jj] - prices[jj]))
  1. public int calculateMax(int[] prices) {
  2. int n = prices.length;
  3. int[][] dp = new int[3][n];
  4. for (int i = 1; i <= 2; i++) {
  5. int localMax = dp[i - 1][0] - prices[0];
  6. for (int j = 1; j < n; j++) {
  7. dp[i][j] = Math.max(dp[i][j - 1], prices[j] + localMax);
  8. localMax = Math.max(localMax, dp[i - 1][j] - prices[j]);
  9. }
  10. }
  11. return dp[2][n - 1];
  12. }

4. 微软-LUCKY STRING

  • 斐波那契数列可以预计算;
  • 从头到尾遍历字符串的过程,每一轮循环都使用一个 Set 来保存从 i 到 j 出现的字符,并且 Set 保证了字符都不同,因此 Set 的大小就是不同字符的个数。
  1. Set<Integer> fibSet = new HashSet<>(Arrays.asList(1, 2, 3, 5, 8, 13, 21, 34, 55, 89));
  2. Scanner in = new Scanner(System.in);
  3. String str = in.nextLine();
  4. int n = str.length();
  5. Set<String> ret = new HashSet<>();
  6. for (int i = 0; i < n; i++) {
  7. Set<Character> set = new HashSet<>();
  8. for (int j = i; j < n; j++) {
  9. set.add(str.charAt(j));
  10. int cnt = set.size();
  11. if (fibSet.contains(cnt)) {
  12. ret.add(str.substring(i, j + 1));
  13. }
  14. }
  15. }
  16. String[] arr = ret.toArray(new String[ret.size()]);
  17. Arrays.sort(arr);
  18. for (String s : arr) {
  19. System.out.println(s);
  20. }

5. 微软-Numeric Keypad

  1. private static int[][] canReach = {
  2. {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 0
  3. {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // 1
  4. {1, 0, 1, 1, 0, 1, 1, 0, 1, 1}, // 2
  5. {0, 0, 0, 1, 0, 0, 1, 0, 0, 1}, // 3
  6. {1, 0, 0, 0, 1, 1, 1, 1, 1, 1}, // 4
  7. {1, 0, 0, 0, 0, 1, 1, 0, 1, 1}, // 5
  8. {0, 0, 0, 0, 0, 0, 1, 0, 0, 1}, // 6
  9. {1, 0, 0, 0, 0, 0, 0, 1, 1, 1}, // 7
  10. {1, 0, 0, 0, 0, 0, 0, 0, 1, 1}, // 8
  11. {0, 0, 0, 0, 0, 0, 0, 0, 0, 1} // 9
  12. };
  13. private static boolean isLegal(char[] chars, int idx) {
  14. if (idx >= chars.length || idx < 0) return true;
  15. int cur = chars[idx] - '0';
  16. int next = chars[idx + 1] - '0';
  17. return canReach[cur][next] == 1;
  18. }
  19. public static void main(String[] args) {
  20. Scanner in = new Scanner(System.in);
  21. int T = Integer.valueOf(in.nextLine());
  22. for (int i = 0; i < T; i++) {
  23. String line = in.nextLine();
  24. char[] chars = line.toCharArray();
  25. for (int j = 0; j < chars.length - 1; j++) {
  26. while (!isLegal(chars, j)) {
  27. if (--chars[j + 1] < '0') {
  28. chars[j--]--;
  29. }
  30. for (int k = j + 2; k < chars.length; k++) {
  31. chars[k] = '9';
  32. }
  33. }
  34. }
  35. System.out.println(new String(chars));
  36. }
  37. }

6. 微软-Spring Outing

下面以 N = 3,K = 4 来进行讨论。

初始时,令第 0 个地方成为待定地点,也就是呆在家里。

从第 4 个地点开始投票,每个人只需要比较第 4 个地方和第 0 个地方的优先级,里,如果超过半数的人选择了第 4 个地方,那么更新第 4 个地方成为待定地点。

从后往前不断重复以上步骤,不断更新待定地点,直到所有地方都已经投票。

上面的讨论中,先令第 0 个地点成为待定地点,是因为这样的话第 4 个地点就只需要和这个地点进行比较,而不用考虑其它情况。如果最开始先令第 1 个地点成为待定地点,那么在对第 2 个地点进行投票时,每个人不仅要考虑第 2 个地点与第 1 个地点的优先级,也要考虑与其后投票地点的优先级。

  1. int N = in.nextInt();
  2. int K = in.nextInt();
  3. int[][] votes = new int[N][K + 1];
  4. for (int i = 0; i < N; i++) {
  5. for (int j = 0; j < K + 1; j++) {
  6. int place = in.nextInt();
  7. votes[i][place] = j;
  8. }
  9. }
  10. int ret = 0;
  11. for (int place = K; place > 0; place--) {
  12. int cnt = 0;
  13. for (int i = 0; i < N; i++) {
  14. if (votes[i][place] < votes[i][ret]) {
  15. cnt++;
  16. }
  17. }
  18. if (cnt > N / 2) {
  19. ret = place;
  20. }
  21. }
  22. System.out.println(ret == 0 ? "otaku" : ret);

7. 微软-S-expression

8. 华为-最高分是多少

  1. int N = in.nextInt();
  2. int M = in.nextInt();
  3. int[] scores = new int[N];
  4. for (int i = 0; i < N; i++) {
  5. scores[i] = in.nextInt();
  6. }
  7. for (int i = 0; i < M; i++) {
  8. String str = in.next();
  9. if (str.equals("U")) {
  10. int id = in.nextInt() - 1;
  11. int newScore = in.nextInt();
  12. scores[id] = newScore;
  13. } else {
  14. int idBegin = in.nextInt() - 1;
  15. int idEnd = in.nextInt() - 1;
  16. int ret = 0;
  17. if (idBegin > idEnd) {
  18. int t = idBegin;
  19. idBegin = idEnd;
  20. idEnd = t;
  21. }
  22. for (int j = idBegin; j <= idEnd; j++) {
  23. ret = Math.max(ret, scores[j]);
  24. }
  25. System.out.println(ret);
  26. }
  27. }

9. 华为-简单错误记录

  1. HashMap<String, Integer> map = new LinkedHashMap<>();
  2. while (in.hasNextLine()) {
  3. String s = in.nextLine();
  4. String key = s.substring(s.lastIndexOf('\\') + 1);
  5. map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1);
  6. }
  7. List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
  8. Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
  9. for (int i = 0; i < 8 && i < list.size(); i++) {
  10. String[] token = list.get(i).getKey().split(" ");
  11. String filename = token[0];
  12. String line = token[1];
  13. if (filename.length() > 16) filename = filename.substring(filename.length() - 16);
  14. System.out.println(filename + " " + line + " " + list.get(i).getValue());
  15. }

10. 华为-扑克牌大小

  1. public class Main {
  2. private Map<String, Integer> map = new HashMap<>();
  3. public Main() {
  4. map.put("3", 0);
  5. map.put("4", 1);
  6. map.put("5", 2);
  7. map.put("6", 3);
  8. map.put("7", 4);
  9. map.put("8", 5);
  10. map.put("9", 6);
  11. map.put("10", 7);
  12. map.put("J", 8);
  13. map.put("Q", 9);
  14. map.put("K", 10);
  15. map.put("A", 11);
  16. map.put("2", 12);
  17. map.put("joker", 13);
  18. map.put("JOKER ", 14);
  19. }
  20. private String play(String s1, String s2) {
  21. String[] token1 = s1.split(" ");
  22. String[] token2 = s2.split(" ");
  23. CardType type1 = computeCardType(token1);
  24. CardType type2 = computeCardType(token2);
  25. if (type1 == CardType.DoubleJoker) return s1;
  26. if (type2 == CardType.DoubleJoker) return s2;
  27. if (type1 == CardType.Bomb && type2 != CardType.Bomb) return s1;
  28. if (type2 == CardType.Bomb && type1 != CardType.Bomb) return s2;
  29. if (type1 != type2 || token1.length != token2.length) return "ERROR";
  30. for (int i = 0; i < token1.length; i++) {
  31. int val1 = map.get(token1[i]);
  32. int val2 = map.get(token2[i]);
  33. if (val1 != val2) return val1 > val2 ? s1 : s2;
  34. }
  35. return "ERROR";
  36. }
  37. private CardType computeCardType(String[] token) {
  38. boolean hasjoker = false, hasJOKER = false;
  39. for (int i = 0; i < token.length; i++) {
  40. if (token[i].equals("joker")) hasjoker = true;
  41. else if (token[i].equals("JOKER")) hasJOKER = true;
  42. }
  43. if (hasjoker && hasJOKER) return CardType.DoubleJoker;
  44. int maxContinueLen = 1;
  45. int curContinueLen = 1;
  46. String curValue = token[0];
  47. for (int i = 1; i < token.length; i++) {
  48. if (token[i].equals(curValue)) curContinueLen++;
  49. else {
  50. curContinueLen = 1;
  51. curValue = token[i];
  52. }
  53. maxContinueLen = Math.max(maxContinueLen, curContinueLen);
  54. }
  55. if (maxContinueLen == 4) return CardType.Bomb;
  56. if (maxContinueLen == 3) return CardType.Triple;
  57. if (maxContinueLen == 2) return CardType.Double;
  58. boolean isStraight = true;
  59. for (int i = 1; i < token.length; i++) {
  60. if (map.get(token[i]) - map.get(token[i - 1]) != 1) {
  61. isStraight = false;
  62. break;
  63. }
  64. }
  65. if (isStraight && token.length == 5) return CardType.Straight;
  66. return CardType.Sigal;
  67. }
  68. private enum CardType {
  69. DoubleJoker, Bomb, Sigal, Double, Triple, Straight;
  70. }
  71. public static void main(String[] args) {
  72. Main main = new Main();
  73. Scanner in = new Scanner(System.in);
  74. while (in.hasNextLine()) {
  75. String s = in.nextLine();
  76. String[] token = s.split("-");
  77. System.out.println(main.play(token[0], token[1]));
  78. }
  79. }
  80. }

11. 去哪儿-二分查找

对于有重复元素的有序数组,二分查找需要注意以下要点:

  • if (val <= A[m]) h = m;
  • 因为 h 的赋值为 m 而不是 m - 1,因此 while 循环的条件也就为 l < h。(如果是 m - 1 循环条件为 l <= h)
  1. public int getPos(int[] A, int n, int val) {
  2. int l = 0, h = n - 1;
  3. while (l < h) {
  4. int m = l + (h - l) / 2;
  5. if (val <= A[m]) h = m;
  6. else l = m + 1;
  7. }
  8. return A[h] == val ? h : -1;
  9. }

12. 去哪儿-首个重复字符

  1. public char findFirstRepeat(String A, int n) {
  2. boolean[] hasAppear = new boolean[256];
  3. for (int i = 0; i < n; i++) {
  4. char c = A.charAt(i);
  5. if(hasAppear[c]) return c;
  6. hasAppear[c] = true;
  7. }
  8. return ' ';
  9. }

13. 去哪儿-寻找Coder

  1. public String[] findCoder(String[] A, int n) {
  2. List<Pair<String, Integer>> list = new ArrayList<>();
  3. for (String s : A) {
  4. int cnt = 0;
  5. String t = s.toLowerCase();
  6. int idx = -1;
  7. while (true) {
  8. idx = t.indexOf("coder", idx + 1);
  9. if (idx == -1) break;
  10. cnt++;
  11. }
  12. if (cnt != 0) {
  13. list.add(new Pair<>(s, cnt));
  14. }
  15. }
  16. Collections.sort(list, (o1, o2) -> (o2.getValue() - o1.getValue()));
  17. String[] ret = new String[list.size()];
  18. for (int i = 0; i < list.size(); i++) {
  19. ret[i] = list.get(i).getKey();
  20. }
  21. return ret;
  22. }
  23. // 牛客网无法导入 javafx.util.Pair,这里就自己实现一下 Pair 类
  24. private class Pair<T, K> {
  25. T t;
  26. K k;
  27. Pair(T t, K k) {
  28. this.t = t;
  29. this.k = k;
  30. }
  31. T getKey() {
  32. return t;
  33. }
  34. K getValue() {
  35. return k;
  36. }
  37. }

14. 美团-最大差值

贪心策略。

  1. public int getDis(int[] A, int n) {
  2. int max = 0;
  3. int soFarMin = A[0];
  4. for (int i = 1; i < n; i++) {
  5. if(soFarMin > A[i]) soFarMin = A[i];
  6. else max = Math.max(max, A[i]- soFarMin);
  7. }
  8. return max;
  9. }

15. 美团-棋子翻转

  1. public int[][] flipChess(int[][] A, int[][] f) {
  2. int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
  3. for (int[] ff : f) {
  4. for (int[] dd : direction) {
  5. int r = ff[0] + dd[0] - 1, c = ff[1] + dd[1] - 1;
  6. if(r < 0 || r > 3 || c < 0 || c > 3) continue;
  7. A[r][c] ^= 1;
  8. }
  9. }
  10. return A;
  11. }

16. 美团-拜访

  1. private Set<String> paths;
  2. private List<Integer> curPath;
  3. public int countPath(int[][] map, int n, int m) {
  4. paths = new HashSet<>();
  5. curPath = new ArrayList<>();
  6. for (int i = 0; i < n; i++) {
  7. for (int j = 0; j < m; j++) {
  8. if (map[i][j] == 1) {
  9. map[i][j] = -1;
  10. int[][] leftRightDirection = {{1, 0}, {-1, 0}};
  11. int[][] topDownDirection = {{0, 1}, {0, -1}};
  12. for (int[] lr : leftRightDirection) {
  13. for (int[] td : topDownDirection) {
  14. int[][] directions = {lr, td};
  15. backtracking(map, n, m, i, j, directions);
  16. }
  17. }
  18. return paths.size();
  19. }
  20. }
  21. }
  22. return 0;
  23. }
  24. private void backtracking(int[][] map, int n, int m, int r, int c, int[][] directions) {
  25. if (map[r][c] == 2) {
  26. String path = "";
  27. for (int num : curPath) {
  28. path += num;
  29. }
  30. paths.add(path);
  31. return;
  32. }
  33. for (int i = 0; i < directions.length; i++) {
  34. int nextR = r + directions[i][0];
  35. int nextC = c + directions[i][1];
  36. if (nextR < 0 || nextR >= n || nextC < 0 || nextC >= m || map[nextR][nextC] == -1) continue;
  37. map[nextR][nextC] = map[nextR][nextC] == 2 ? 2 : -1;
  38. curPath.add(nextR);
  39. curPath.add(nextC);
  40. backtracking(map, n, m, nextR, nextC, directions);
  41. curPath.remove(curPath.size() - 1);
  42. curPath.remove(curPath.size() - 1);
  43. map[nextR][nextC] = map[nextR][nextC] == 2 ? 2 : 0;
  44. }
  45. }

17. 美团-直方图内最大矩形

  1. public int countArea(int[] A, int n) {
  2. int max = 0;
  3. for (int i = 0; i < n; i++) {
  4. int min = A[i];
  5. for (int j = i; j < n; j++) {
  6. min = Math.min(min, A[j]);
  7. max = Math.max(max, min * (j - i + 1));
  8. }
  9. }
  10. return max;
  11. }

18. 美团-字符串计数

字符串都是小写字符,可以把字符串当成是 26 进制。但是字典序的比较和普通的整数比较不同,是从左往右进行比较,例如 “ac” 和 “abc”,字典序的比较结果为 “ac” > “abc”,如果按照整数方法比较,因为 “abc” 是三位数,显然更大。

由于两个字符串的长度可能不想等,在 s1 空白部分和 s2 对应部分进行比较时,应该把 s1 的空白部分看成是 ‘a’ 字符进行填充的。

还有一点要注意的是,s1 到 s2 长度为 leni 的字符串个数只比较前面 i 个字符。例如 ‘aaa’ 和 ‘bbb’ ,长度为 2 的个数为 ‘aa’ 到 ‘bb’ 的字符串个数,不需要考虑后面部分的字符。

在统计个数时,从 len1 开始一直遍历到最大合法长度,每次循环都统计长度为 i 的子字符串个数。

  1. String s1 = in.next();
  2. String s2 = in.next();
  3. int len1 = in.nextInt();
  4. int len2 = in.nextInt();
  5. int len = Math.min(s2.length(), len2);
  6. int[] subtractArr = new int[len];
  7. for (int i = 0; i < len; i++) {
  8. char c1 = i < s1.length() ? s1.charAt(i) : 'a';
  9. char c2 = s2.charAt(i);
  10. subtractArr[i] = c2 - c1;
  11. }
  12. int ret = 0;
  13. for (int i = len1; i <= len; i++) {
  14. for (int j = 0; j < i; j++) {
  15. ret += subtractArr[j] * Math.pow(26, i - j - 1);
  16. }
  17. }
  18. System.out.println(ret - 1);

19. 美团-平均年龄

  1. int W = in.nextInt();
  2. double Y = in.nextDouble();
  3. double x = in.nextDouble();
  4. int N = in.nextInt();
  5. while (N-- > 0) {
  6. Y++; // 老员工每年年龄都要加 1
  7. Y += (21 - Y) * x;
  8. }
  9. System.out.println((int) Math.ceil(Y));

20. 百度-罪犯转移

部分和问题,将每次求的部分和缓存起来。

  1. int n = in.nextInt();
  2. int t = in.nextInt();
  3. int c = in.nextInt();
  4. int[] values = new int[n];
  5. for (int i = 0; i < n; i++) {
  6. values[i] = in.nextInt();
  7. }
  8. int cnt = 0;
  9. int totalValue = 0;
  10. for (int s = 0, e = c - 1; e < n; s++, e++) {
  11. if (s == 0) {
  12. for (int j = 0; j < c; j++) totalValue += values[j];
  13. } else {
  14. totalValue = totalValue - values[s - 1] + values[e];
  15. }
  16. if (totalValue <= t) cnt++;
  17. }
  18. System.out.println(cnt);

22. 百度-裁减网格纸

  1. int n = in.nextInt();
  2. int minX, minY, maxX, maxY;
  3. minX = minY = Integer.MAX_VALUE;
  4. maxX = maxY = Integer.MIN_VALUE;
  5. for (int i = 0; i < n; i++) {
  6. int x = in.nextInt();
  7. int y = in.nextInt();
  8. minX = Math.min(minX, x);
  9. minY = Math.min(minY, y);
  10. maxX = Math.max(maxX, x);
  11. maxY = Math.max(maxY, y);
  12. }
  13. System.out.println((int) Math.pow(Math.max(maxX - minX, maxY - minY), 2));

23. 百度-钓鱼比赛

P ( 至少钓一条鱼 ) = 1 - P ( 一条也钓不到 )

坑:读取概率矩阵的时候,需要一行一行进行读取,而不能直接用 in.nextDouble()。

  1. public static void main(String[] args) {
  2. Scanner in = new Scanner(System.in);
  3. while (in.hasNext()) {
  4. int n = in.nextInt();
  5. int m = in.nextInt();
  6. int x = in.nextInt();
  7. int y = in.nextInt();
  8. int t = in.nextInt();
  9. in.nextLine(); // 坑
  10. double pcc = 0.0;
  11. double sum = 0.0;
  12. for (int i = 1; i <= n; i++) {
  13. String[] token = in.nextLine().split(" "); // 坑
  14. for (int j = 1; j <= m; j++) {
  15. double p = Double.parseDouble(token[j - 1]);
  16. // double p = in.nextDouble();
  17. sum += p;
  18. if (i == x && j == y) {
  19. pcc = p;
  20. }
  21. }
  22. }
  23. double pss = sum / (n * m);
  24. pcc = computePOfIRT(pcc, t);
  25. pss = computePOfIRT(pss, t);
  26. System.out.println(pcc > pss ? "cc" : pss > pcc ? "ss" : "equal");
  27. System.out.printf("%.2f\n", Math.max(pcc, pss));
  28. }
  29. }
  30. // compute probability of independent repeated trials
  31. private static double computePOfIRT(double p, int t) {
  32. return 1 - Math.pow((1 - p), t);
  33. }

24. 百度-蘑菇阵

这题用回溯会超时,需要用 DP。

dp[i][j] 表示到达 (i,j) 位置不会触碰蘑菇的概率。对于 N*M 矩阵,如果 i == N || j == M,那么 (i,j) 只能有一个移动方向;其它情况下能有两个移动方向。

考虑以下矩阵,其中第 3 行和第 3 列只能往一个方向移动,而其它位置可以有两个方向移动。

  1. int N = in.nextInt();
  2. int M = in.nextInt();
  3. int K = in.nextInt();
  4. boolean[][] mushroom = new boolean[N][M];
  5. while (K-- > 0) {
  6. int x = in.nextInt();
  7. int y = in.nextInt();
  8. mushroom[x - 1][y - 1] = true;
  9. }
  10. double[][] dp = new double[N][M];
  11. dp[0][0] = 1;
  12. for (int i = 0; i < N; i++) {
  13. for (int j = 0; j < M; j++) {
  14. if (mushroom[i][j]) dp[i][j] = 0;
  15. else {
  16. double cur = dp[i][j];
  17. if (i == N - 1 && j == M - 1) break;
  18. if (i == N - 1) dp[i][j + 1] += cur;
  19. else if (j == M - 1) dp[i + 1][j] += cur;
  20. else {
  21. dp[i][j + 1] += cur / 2;
  22. dp[i + 1][j] += cur / 2;
  23. }
  24. }
  25. }
  26. }
  27. System.out.printf("%.2f\n", dp[N - 1][M - 1]);