我正在学习java,当我需要查找数组中每个数字的节目数时,我有一个练习,数字是0-100,这需要在O(n)中完成。现在我不知道如何做到这一点,所以我看到了解决方案,并没有真正理解它,解决方案的解释非常差,这里是代码:
public static void count (int [] data){
final int N = 100;
int [] temp = new int[N];
int i;
for (i=0; i < data.length; i++){
temp[data[i]]+=1;
}
for (i=0; i < N; i++){
if ( temp[i] != 0)
System.out.println(i + ":" +temp[i]);
}
}
我特意没有得到这条线
temp[data[i]]+=1;
如果有人可以向我解释代码中每一行的想法, 我非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
基本上,该代码执行此操作: 1)初始化具有100个位置的临时数组(全部设置为0); 2)迭代数据数组并相对于它正在处理的数据数组值的索引递增值。举个例子:
int[] data = {23,11,10,23,5};
temp[data[0]] += 1
temp[23] += 1
temp[23] = temp[23] + 1 = 0 + 1 = 1
temp[data[1]] += 1
temp[11] += 1
temp[11] = temp[11] + 1 = 0 + 1 = 1
temp[data[2]] += 1
temp[10] += 1
temp[10] = temp[10] + 1 = 0 + 1 = 1
temp[data[3]] += 1
temp[23] += 1
temp[23] = temp[23] + 1 = 1 + 1 = 2
temp[data[4]] += 1
temp[5] += 1
temp[5] = temp[5] + 1 = 0 + 1 = 1
因此,在这种情况下,您会注意到值23在数据数组中出现两次,而其他值只出现一次。这样,您可以计算O(n)中的出现次数,也就是说,只需遍历一次数组。
答案 1 :(得分:0)
/* method signature
static - method can be used without instantiation of the class
public - can be accessed by other classes
void - the return of the function count.
int [] data - parameter of the function. This function receives an array of int
*/
public static void count (int [] data){
final int N = 100;
int [] temp = new int[N];
int i;
//for i = 0 until i < size of the array passed as parameter, increment 1 in i
for (i=0; i < data.length; i++){
/*
each iteration of this for increments 1 in the array temp at the position informed by the value of parameter data in position i.
caution: this can bring serious problems of segmentation fault, in other words, you can try to store in a position of the array temp that doesn't exist.
This will happen because you cannot guarantee the number that will be store in data[i]. If data[i] > 99 (because N = 100), you will face a segmentation fault.
*/
temp[data[i]]+=1;
}
//here you will print the value stored at temp array in position i. From 0 to 99
for (i=0; i < N; i++)
{
if ( temp[i] != 0)
System.out.println(i + ":" +temp[i]);
}
}
HOPE IT HELPS.
You need to study more. Your question is so naive.