Microsoft VO 面试真题解析:统计 1 到 N 每个数字出现次数

30次阅读
没有评论

Given an array of N integers containing integers from 1 to N only. Some numbers may appear multiple times, some numbers may not appear.

Write code to print out the count of times each number from 1 to N appears in the array. For example:

PrintFrequency(new int[] {3, 1, 2});
1 : 1
2 : 1
3 : 1
PrintFrequency(new int[] {2, 4, 4, 6, 6, 6});
1 : 0
2 : 1
3 : 0
4 : 2
5 : 0
6 : 3

这道题的核心是统计数组中 1 到 N 每个数字的出现次数。最直接的做法是用一个长度为 N 的计数数组,遍历原数组时将对应位置加一,最后按 1 到 N 的顺序输出结果即可。这样时间复杂度是 O(N),空间复杂度是 O(N),实现简单且非常适合面试中的基础频次统计场景。

正文完
 0