如何使用简单的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;
}
答案 0 :(得分:4)
首先,我按顺序对数组进行排序,然后计算一个数字的出现次数。没有用于循环和if语句的哈希映射。
我的代码:
static int Mode(int[] n){
int t = 0;
for(int i=0; i<n.length; i++){
for(int j=1; j<n.length-i; j++){
if(n[j-1] > 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<n.length;i++){
if(n[i-1] == n[i]){
temp++;
}
else {
temp = 1;
}
if(temp >= temp2){
mode = n[i];
temp2 = temp;
}
}
return mode;
}
答案 1 :(得分:3)
- 只需使用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-&gt; 4,2-&gt; 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<arr.length; i++)
{
double currentIndexVal = arr[i];
if(arrayVals.containsKey(currentIndexVal)){
int currentOccurencesNum = (Integer) arrayVals.get(currentIndexVal);
currentOccurencesNum++;
arrayVals.put(currentIndexVal, currentOccurencesNum );
if(currentOccurencesNum >= maxOccurences)
{
mode = currentIndexVal;
maxOccurences = currentOccurencesNum;
}
}
else{
arrayVals.put(arr[i], 1);
}
}
return mode;
}
答案 2 :(得分:1)
此代码是一种不使用散列图的不同方式。在java中创建的此方法将数组作为参数,并创建另一个名为&#34; numberCount&#34;的数组。在方法内。这个数组&#34; numberCount&#34;将其索引设置为数组中的值。包含传递的数组中的值的&#34; numberCount&#34;的索引将为&#34; numberCount&#34;的值加1。 (&#34; ++ numberCount [array [i]]&#34;)然后将转到数组中的下一个值(重复直到数组结束)。然后创建另一个for循环以遍历&#34; numberCount&#34;中的数组的每个值,其中索引具有最高值/计数将被存储并返回为&#34; max。&#34;这种方法必须经过一些艰难的改变才能使用双数组。但似乎使用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;
}
答案 3 :(得分:0)
您应该检查数组中每个元素的出现次数。你可以通过比较数组的每个元素与她自己和其他元素通过2个内部for循环来做到这一点。
请记住,如果数组未排序并且包含多于1个模态值(因此重复出现次数),则返回第一个。最好先通过 Arrays.sort(array)对数组进行排序,这样就可以选择最小或最大的模态值。
public static int modeOfArray(int[] array){
int mode;
int maxOccurance = 0;
for(int i=0; i<array.length; i++){
int occuranceOfThisValue = 0;
for(int j=0; j<array.length; j++){
if(array[i] == array[j])
occuranceOfThisValue++;
}
if(occuranceOfThisValue > maxOccurance){
maxOccurance = occuranceOfThisValue;
mode = array[i];
}
}
return mode;
}