.
[color=olive]今天上[/color][color=red]谯老师[/color][color=olive]软件项目管理方法与实践课时给出了一个他曾经留美的面试题目:统计某一数组中重复数字的次数,其实不难但是觉得非常的有意思,毕竟是他曾经留洋的面试题嘛!方法类似于我的上一篇博文[/color][url=http://ocaicai.iteye.com/blog/1018597]模仿String.indexOf,判断一个字符串是否包含另一个字符串[/url][color=olive],虽然可以在一个方法中,但是多几个方法看上去层次会更清晰一点!下面是源码及输出结果![/color]
[color=red]输出结果:[/color]
.
[color=olive]今天上[/color][color=red]谯老师[/color][color=olive]软件项目管理方法与实践课时给出了一个他曾经留美的面试题目:统计某一数组中重复数字的次数,其实不难但是觉得非常的有意思,毕竟是他曾经留洋的面试题嘛!方法类似于我的上一篇博文[/color][url=http://ocaicai.iteye.com/blog/1018597]模仿String.indexOf,判断一个字符串是否包含另一个字符串[/url][color=olive],虽然可以在一个方法中,但是多几个方法看上去层次会更清晰一点!下面是源码及输出结果![/color]
import java.util.Random;
/**
* @author 761642812@qq.com
*
*@see 统计某一数组中重复数字的次数. 本例为:数组长度为100,取值范围NUMBERWIDTH为整数[0,20]
*
*/
public class CountTimes {
// 定义数组
private static int intArray[] = new int[100];
// 数字包括的范围
private static final int NUMBERWIDTH = 21;
public static void main(String[] args) {
countEveryNumberTimes(setArray(intArray));
}
// 初始化数组:使用随机数为数组赋值
public static int[] setArray(int[] array) {
for (int i = 0; i < 100; i++) {
int randomNum = new Random().nextInt(NUMBERWIDTH);
array[i] = randomNum;
}
// 调用打印数组方法
printSingleArray(array);
return array;
}
// 控制输出打印一维数组
public static void printSingleArray(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i % 10 == 0) {
System.out.println();
} else {
if (array[i] > 9) {
System.out.print(array[i] + " ");
} else {
System.out.print("0" + array[i] + " ");
}
}
}
System.out.println();
}
// 统计某一个特定的数在某一数组中出现的次数
public static int countSpecifyNumberTimes(int specifyNumber, int[] array) {
int specifyCountTimes = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifyNumber) {
specifyCountTimes++;
}
}
return specifyCountTimes;
}
// 统计每一个数字出现的次数
public static void countEveryNumberTimes(int[] array) {
for (int i = 0; i < NUMBERWIDTH; i++) {
int specifyCountTimes = countSpecifyNumberTimes(i, array);
if (specifyCountTimes > 0) {
System.out.println("数字" + i + "出现的次数为:" + specifyCountTimes);
}
}
}
}
[color=red]输出结果:[/color]
16 10 02 11 15 14 14 00 03
10 08 03 18 17 17 17 10 18
11 20 14 13 03 20 00 20 17
14 12 19 09 20 10 03 10 14
20 02 04 10 19 17 18 18 20
17 16 19 05 11 09 01 13 18
03 13 07 14 08 00 15 20 15
08 07 08 20 02 11 09 09 04
08 19 14 06 09 01 01 10 18
11 05 16 15 07 05 18 09 08
数字0出现的次数为:4
数字1出现的次数为:3
数字2出现的次数为:3
数字3出现的次数为:8
数字4出现的次数为:3
数字5出现的次数为:3
数字6出现的次数为:1
数字7出现的次数为:3
数字8出现的次数为:6
数字9出现的次数为:6
数字10出现的次数为:9
数字11出现的次数为:6
数字12出现的次数为:1
数字13出现的次数为:3
数字14出现的次数为:7
数字15出现的次数为:4
数字16出现的次数为:3
数字17出现的次数为:7
数字18出现的次数为:8
数字19出现的次数为:4
数字20出现的次数为:8
.