在Java中编写模式方法以查找数组中最常出现的元素

问题是:

编写一个名为mode的方法,它返回整数数组中最常出现的元素。 假设数组至少有一个元素,并且数组中的每个元素都具有0到100之间的值(包括0和100)。 通过选择较低的值来打破联系。

例如,如果传递的数组包含值{27,15,15,11,27},则您的方法应返回15.(提示:您可能希望查看本章前面的Tally程序以了解如何解决这个问题呢。)

下面是我的代码几乎可以工作,除了单元素数组

public static int mode(int[] n) {     Arrays.sort(n);     int count2 = 0; int count1 = 0; int pupular1 =0; int popular2 =0; for (int i = 0; i < n.length; i++) { pupular1 = n[i]; count1 = 0; //see edit for (int j = i + 1; j  count2) { popular2 = pupular1; count2 = count1; } else if(count1 == count2) { popular2 = Math.min(popular2, pupular1); } } return popular2; } 

编辑 :终于搞清楚了。 改变count1 = 0;count1 = 1; 现在一切正常!

你应该使用hashmap来解决这些问题。 将每个元素输入到散列映射中需要O(n)时间,并且需要o(1)来检索元素。 在给定的代码中,我基本上采用全局最大值并将其与从散列映射中的’get’接收的值进行比较,每次我在其中输入元素时,看看:

hashmap有两个部分,一个是键,第二个是对键执行get操作时的值,返回其值。

 public static int mode(int []array) { HashMap hm = new HashMap(); int max = 1; int temp = 0; for(int i = 0; i < array.length; i++) { if (hm.get(array[i]) != null) { int count = hm.get(array[i]); count++; hm.put(array[i], count); if(count > max) { max = count; temp = array[i]; } } else hm.put(array[i],1); } return temp; } 

您应该能够在N次操作中执行此操作,这意味着只需一次传递O(n)时间。

使用map或int [](如果问题仅针对int)增加计数器,并使用保持具有最大计数的键的变量。 每次递增计数器时,询问该值是什么,并将其与您上次使用的密钥进行比较,如果值较大则更新密钥。

 public class Mode { public static int mode(final int[] n) { int maxKey = 0; int maxCounts = 0; int[] counts = new int[n.length]; for (int i=0; i < n.length; i++) { counts[n[i]]++; if (maxCounts < counts[n[i]]) { maxCounts = counts[n[i]]; maxKey = n[i]; } } return maxKey; } public static void main(String[] args) { int[] n = new int[] { 3,7,4,1,3,8,9,3,7,1 }; System.out.println(mode(n)); } } 
 public int mode(int[] array) { int mode = array[0]; int maxCount = 0; for (int i = 0; i < array.length; i++) { int value = array[i]; int count = 1; for (int j = 0; j < array.length; j++) { if (array[j] == value) count++; if (count > maxCount) { mode = value; maxCount = count; } } } return mode; } 

检查这个..简介:选择数组的每个元素并将其与数组的所有元素进行比较,天气等于拾取或不接收。

  int popularity1 = 0; int popularity2 = 0; int popularity_item, array_item; //Array contains integer value. Make it String if array contains string value. for(int i =0;i= popularity2){ popularity_item = array_item; popularity2 = popularity1; } popularity1 = 0; } //"popularity_item" contains the most repeted item in an array. 

我会用这个代码。 它包含一个instancesOf函数,它贯穿每个数字。

 public class MathFunctions { public static int mode(final int[] n) { int maxKey = 0; int maxCounts = 0; for (int i : n) { if (instancesOf(i, n) > maxCounts) { maxCounts = instancesOf(i, n); maxKey = i; } } return maxKey; } public static int instancesOf(int n, int[] Array) { int occurences = 0; for (int j : Array) { occurences += j == n ? 1 : 0; } return occurences; } public static void main (String[] args) { //TODO Auto-generated method stub System.out.println(mode(new int[] {100,200,2,300,300,300,500})); } } 

我注意到Gubatron发布的代码在我的电脑上无效; 它给了我一个ArrayIndexOutOfBoundsException

这是我的答案。

 public static int mode(int[] arr) { int max = 0; int maxFreq = 0; Arrays.sort(arr); max = arr[arr.length-1]; int[] count = new int[max + 1]; for (int i = 0; i < arr.length; i++) { count[arr[i]]++; } for (int i = 0; i < count.length; i++) { if (count[i] > maxFreq) { maxFreq = count[i]; } } for (int i = 0; i < count.length; i++) { if (count[i] == maxFreq) { return i; } } return -1; } 

我知道这个问题是从不久前开始的,但我想补充一个我认为扩展到原始问题的答案。 这个问题的补充是在不依赖预设范围的情况下编写模式方法(在本例中为0到100)。 我编写了一个模式版本,它使用原始数组中的值范围来生成计数数组。

 public static int mode(int[] list) { //Initialize max and min value variable as first value of list int maxValue = list[0]; int minValue = list[0]; //Finds maximum and minimum values in list for (int i = 1; i < list.length; i++) { if (list[i] > maxValue) { maxValue = list[i]; } if (list[i] < minValue) { minValue = list[i]; } } //Initialize count array with (maxValue - minValue + 1) elements int[] count = new int[maxValue - minValue + 1]; //Tally counts of values from list, store in array count for (int i = 0; i < list.length; i++) { count[list[i] - minValue]++; //Increment counter index for current value of list[i] - minValue } //Find max value in count array int max = count[0]; //Initialize max variable as first value of count for (int i = 1; i < count.length; i++) { if (count[i] > max) { max = count[i]; } } //Find first instance where max occurs in count array for (int i = 0; i < count.length; i++) { if (count[i] == max) { return i + minValue; //Returns index of count adjusted for min/max list values - this is the mode value in list } } return -1; //Only here to force compilation, never actually used } 

我最近制作了一个程序来计算一些不同的统计数据,包括模式。 虽然编码可能是基本的,但它适用于任何int数组,并且可以修改为double,float等。对数组的修改基于删除数组中不是最终模式值的索引。 这允许您显示所有模式(如果有多个)以及具有发生的数量(模式数组中的最后一项)。 下面的代码是getMode方法以及运行此代码所需的deleteValueIndex方法

 import java.io.File; import java.util.Scanner; import java.io.PrintStream; public static int[] getMode(final int[] array) { int[] numOfVals = new int[array.length]; int[] valsList = new int[array.length]; //initialize the numOfVals and valsList for(int ix = 0; ix < array.length; ix++) { valsList[ix] = array[ix]; } for(int ix = 0; ix < numOfVals.length; ix++) { numOfVals[ix] = 1; } //freq table of items in valsList for(int ix = 0; ix < valsList.length - 1; ix++) { for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) { if(valsList[ix2] == valsList[ix]) { numOfVals[ix] += 1; } } } //deletes index from valsList and numOfVals if a duplicate is found in valsList for(int ix = 0; ix < valsList.length - 1; ix++) { for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) { if(valsList[ix2] == valsList[ix]) { valsList = deleteValIndex(valsList, ix2); numOfVals = deleteValIndex(numOfVals, ix2); } } } //finds the highest occurence in numOfVals and sets it to most int most = 0; for(int ix = 0; ix < valsList.length; ix++) { if(numOfVals[ix] > most) { most = numOfVals[ix]; } } //deletes index from valsList and numOfVals if corresponding index in numOfVals is less than most for(int ix = 0; ix < numOfVals.length; ix++) { if(numOfVals[ix] < most) { valsList = deleteValIndex(valsList, ix); numOfVals = deleteValIndex(numOfVals, ix); ix--; } } //sets modes equal to valsList, with the last index being most(the highest occurence) int[] modes = new int[valsList.length + 1]; for(int ix = 0; ix < valsList.length; ix++) { modes[ix] = valsList[ix]; } modes[modes.length - 1] = most; return modes; } public static int[] deleteValIndex(int[] array, final int index) { int[] temp = new int[array.length - 1]; int tempix = 0; //checks if index is in array if(index >= array.length) { System.out.println("I'm sorry, there are not that many items in this list."); return array; } //deletes index if in array for(int ix = 0; ix < array.length; ix++) { if(ix != index) { temp[tempix] = array[ix]; tempix++; } } return temp; } 

基于@ codemania23和Java Docs for HashMap的答案,我编写了这段代码剪切并测试了一个方法,该方法返回数字数组中最大的当前数字。

 import java.util.HashMap; public class Example { public int mostOcurrentNumber(int[] array) { HashMap map = new HashMap<>(); int result = -1, max = 1; for (int arrayItem : array) { if (map.putIfAbsent(arrayItem, 1) != null) { int count = map.get(arrayItem) + 1; map.put(arrayItem, count); if (count > max) { max = count; result = arrayItem; } } } return result; } } 

unit testing

 import org.junit.Test; import static junit.framework.Assert.assertEquals; public class ExampleTest extends Example { @Test public void returnMinusOneWhenInputArrayIsEmpty() throws Exception { int[] array = new int[0]; assertEquals(mostOcurrentNumber(array), -1); } @Test public void returnMinusOneWhenElementsUnique() { int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; assertEquals(-1, mostOcurrentNumber(array)); } @Test public void returnOne() throws Exception { int[] array = new int[]{0, 1, 0, 0, 1, 1, 1}; assertEquals(1, mostOcurrentNumber(array)); } @Test public void returnFirstMostOcurrentNumber() throws Exception { int[] array = new int[]{0, 1, 0, 1, 0, 0, 1, 1}; assertEquals(0, mostOcurrentNumber(array)); } } 

这不是围绕块的最快的方法,但是如果你不想让自己参与HashMaps并且也想避免使用2 for循环来解决复杂性问题,那么理解起来相当简单….

  int mode(int n, int[] ar) { int personalMax=1,totalMax=0,maxNum=0; for(int i=0;i 

在这里,我使用单循环编码。 我们从[j-1]获得模式,因为当j是j-1时,localCount最近更新了。 N也是数组的大小,计数初始化为0。

  //After sorting the array i = 0,j=0; while(i!=N && j!=N){ if(ar[i] == ar[j]){ localCount++; j++; } else{ i++; localCount = 0; } if(localCount > globalCount){ globalCount = localCount; mode = ar[j-1]; } } 
  Arrays.sort(arr); int max=0,mode=0,count=0; for(int i=0;imax) { max=count; mode = arr[i]; } } 

import java.util.HashMap;

public class SmallestHighestRepeatedNumber {static int arr [] = {9,4,5,9,2,9,1,2,8,1,1,7,7};

 public static void main(String[] args) { int mode = mode(arr); System.out.println(mode); } public static int mode(int[] array) { HashMap hm = new HashMap(); int max = 1; int temp = 0; for (int i = 0; i < array.length; i++) { if (hm.get(array[i]) != null) { int count = hm.get(array[i]); count++; hm.put(array[i], count); if (count > max || temp > array[i] && count == max) { temp = array[i]; max = count; } } else hm.put(array[i], 1); } return temp; } 

}

本代码计算模式,中间和平均值。 它被测试并且它工作。 这是一个从头到尾完整的程序,将编译。

 import java.util.Arrays; import java.util.Random; import java.math.*; /** * * @author Mason */ public class MODE{ public static void main(String args[]) { System.out.print("Enter the quantity of random numbers ===>> "); int listSize = Expo.enterInt(); System.out.println(); ArrayStats intStats = new ArrayStats(listSize); intStats.randomize(); intStats.computeMean(); intStats.computeMedian(); intStats.computeMode(); intStats.displayStats(); System.out.println(); } } class ArrayStats { private int list[]; private int size; private double mean; private double median; private int mode; public ArrayStats(int s)//initializes class object { size = s; list = new int[size]; } public void randomize() { //This will provide same numbers every time... If you want to randomize this, you can Random rand = new Random(555); for (int k = 0; k < size; k++) list[k] = rand.nextInt(11) + 10; } public void computeMean() { double accumulator=0; for (int index=0;index= popularity2){ mode = array_item; popularity2 = popularity1; } popularity1 = 0; }} public void displayStats() { System.out.println(Arrays.toString(list)); System.out.println(); System.out.println("Mean: " + mean); System.out.println("Median: " + median); System.out.println("Mode: " + mode); System.out.println(); } }