我收到了一份作业,我的教授给了我代码,但我必须在指定的行中填写答案才能完成代码
我在问题中得到了固定数组 但是当我重新排列数组中数字的位置时 我的算法不起作用
这是我的代码:
class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 2, 3, 3, 3, 3};
int maxCnt = Integer.MIN_VALUE;
int mem = arr[0];
int cur = arr[0];
int curCnt = 1;//you can modify this line with any value but it has to be curCnt =
int mode = arr[0];
int i;
for(i=1;i<arr.length;i++) {
cur = arr[i];
if(cur == mem) {
curCnt++;
}
else {
if(curCnt > maxCnt) {
mode = mem;
maxCnt = curCnt;
}
/*mem = cur; you can modify in these two lines
curCnt = 1;*/
}
}
if(curCnt > maxCnt/*you can modify in this block*/) {
mode = mem;
maxCnt = curCnt;
}
System.out.printf("mode = %d%nfreq = %d", mode, maxCnt);
}
}
答案必须填写在我在代码中注释的地方
class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 2, 3, 3, 3, 3};
int maxCnt = Integer.MIN_VALUE;
int mem = arr[0];
int cur = arr[0];
int curCnt = 1;
int mode = arr[0];
for(int i=1;i<arr.length;i++) {
cur = arr[i];
if(cur == mem) {
curCnt++;
}
else {
if(curCnt > maxCnt) {
mode = mem;
maxCnt = curCnt;
}
// uncomment this lines it will work fine
mem = cur;
curCnt = 1;
}
}
if(curCnt > maxCnt) {
mode = mem;
maxCnt = curCnt;
}
System.out.printf("mode = %d%nfreq = %d", mode, maxCnt);
}
}
The output produced is :-
mode = 3
freq = 4