使用简单的for循环查找模式(数组中最常见的值)?

如何使用简单的for循环找到模式(数组中最常见的值)?

代码编译错误的输出。

这是我有的:

public static void mode(double [] arr) { double mode=arr[0]; for(int i = 1; i<arr.length; i++) { if(mode==arr[i]) { mode++; } } return mode; } 

首先,我按顺序对数组进行排序,然后计算一个数字的出现次数。 没有hashmap只用于循环和if语句。

我的代码:

 static int Mode(int[] n){ int t = 0; for(int i=0; i n[j]){ t = n[j-1]; n[j-1] = n[j]; n[j] = t; } } } int mode = n[0]; int temp = 1; int temp2 = 1; for(int i=1;i= temp2){ mode = n[i]; temp2 = temp; } } return mode; } 

– 只需使用HashMap,它包含数组索引值作为键,它们的出现次数作为值。

– 在遍历for循环时通过检查当前索引是否已存在于HashMap中来更新HashMap。 如果它然后在哈希映射中找到双重并查看它已经发生了多少次,并将其重新放回HashMap中。

– 我是用Java做的,因为这就是你正在使用的东西。 同样好的是时间复杂度是O(n),这是你可能为这种类型的场景获得的最好的,因为你必须至少访问一次每个元素。

– 如果你有一个像这样的双打数组:{1,2,3,1,1,1,5,5,5,7,7,7,7,7,7,7,7,7}那么哈希映射在最后看起来像这样:{1-> 4,2-> 1,3-> 1,5-> 3,7-> 9}意思是“1发生4次,2次发生1次…. 7发生了9次“等

  public static double mode(double [] arr) { HashMap arrayVals = new HashMap(); int maxOccurences = 1; double mode = arr[0]; for(int i = 0; i= maxOccurences) { mode = currentIndexVal; maxOccurences = currentOccurencesNum; } } else{ arrayVals.put(arr[i], 1); } } return mode; } 

此代码是一种不使用散列图的不同方式。 在java中创建的此方法将数组作为参数,并在方法中创建另一个名为“numberCount”的数组。 此数组“numberCount”将其索引设置为数组中的值。 包含传递的数组中的值的“numberCount”索引将向“numberCount”(“++ numberCount [array [i]]”的值加1,然后将转到数组中的下一个值(重复直到数组的结尾)。 然后创建另一个for循环以遍历“numberCount”中数组的每个值,其中索引具有最高值/计数将被存储并返回为“max”。 此方法必须经历一些困难的更改才能使用双数组。 但似乎使用int数组很好。

 public static int findMostFrequentValue(int[] array) { int i; int[] numberCount = new int[100]; for (i = 0; i < array.length; i++)++numberCount[array[i]]; int max = 0; int j; for (j = 0; j < numberCount.length; j++) { if (numberCount[j] > max) max = j; } return max; } 

您应该检查数组中每个元素的出现次数。 你可以通过2个内部for循环比较数组的每个元素与她自己和其他元素。

请记住,如果数组未排序并包含多于1个模态值(因此重复出现次数),则返回第一个。 首先通过Arrays.sort(数组)对数组进行排序可能是明智的,这样您就可以选择最小或最大的模态值。

 public static int modeOfArray(int[] array){ int mode; int maxOccurance = 0; for(int i=0; i maxOccurance){ maxOccurance = occuranceOfThisValue; mode = array[i]; } } return mode; }