美团笔试3.26
第一题思路:(AC)
由于输入的数字很长,用String接收,然后用hashMap记录数字对应关系。
(回复中有同学用数组代替hashMap,根据数组下标找对应转化后的数字,感觉更好一点(感谢Scale的解答))
注意的点:首位可能是+/-,做单独判断。
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String start = sc.nextLine(); HashMap<Integer, Integer> nums = new HashMap<>(); for (int i = 1; i <= 9; i++) { nums.put(i, sc.nextInt()); } sc.close(); StringBuilder sb = new StringBuilder(); int i = 0; if(start.charAt(0) == '+' || start.charAt(0) == '-'){ sb.append(start.charAt(0)); i++; } for (; i < start.length(); i++) { sb.append(nums.get(start.charAt(i) - '0')); } System.out.println(sb.toString()); }
第二题思路:(AC)
保证最外圈是黑环,所以最里圈可能是白色,根据输入数量n判断里圈是黑还是白,按两种方式求解。
注意的点:
- 输入的半径数组可能是无序的,如:1 3 5 2 4 8。所以要对接收的数组先排序,再计算;
- pi如果用3.1415926部分用例通不过,要用Math.PI。
- 保留小数点5位要记住这个方法:String.format("%.5f", res).
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] rs = new int[n]; for (int i = 0; i < n; i++) { rs[i] = sc.nextInt(); } sc.close(); Arrays.sort(rs); double res = 0.0; if(n % 2 == 1) { res = rs[0] * rs[0]; for (int i = 1; i < n; i++) { if (i + 1 < n) res += rs[i + 1] * rs[i + 1] - rs[i] * rs[i]; i++; } }else { for (int i = n - 1; i >= 0; i--) { res += rs[i] * rs[i] - rs[i - 1] * rs[i - 1]; i--; } } res *= Math.PI; System.out.println(String.format("%.5f", res)); }第三题和第四题都是暴力解法,楼主只过了18,所以不贴代码,求大神解答。
第五题思路:(动态规划的思路,但只过了45)AC解请看评论区 @陈怡-miaow 的回复和 @牛客157007370号 的评论
- dp建一个k+1行、N列的数组;
- dp第一行数组的值就是输入的数组,第一列的所有值相等,都是dp[0][0];
- 递推公式:dp[i][j] = dp[i][j - 1] + dp[i - 1][j],即当前数字等于左边的数加上上面的数。
- 但这样写会出现内存超出情况,所以优化dp:只保留2行,第一行为上一次计算结果,第二行为目前计算的结果,当前计算结束后复制第二行到第一行
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int k = sc.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = sc.nextInt(); } sc.close(); long[][] res = new long[2][N]; for (int j = 0; j < N; j++) { res[0][j] = (long) a[j]; } res[1][0] = res[0][0]; for (int i = 1; i < k + 1; i++) { for (int j = 1; j < N; j++) { res[1][j] = res[1][j - 1] + res[0][j]; } for (int m = 1; m < N; m++) { res[0][m] = res[1][m]; } } System.out.println(res[1][N - 1]); }