algorithm - Least common integer java? -
this question has answer here:
how can detect opposite of mode in java?
for instance, if wanted find least common number in array of numbers, how go doing that?
thanks.
what i've tried:
public int getleastcommonnum(int[] array) { int min = array[0]; int pos = 0; (int = 1; < array.length; i++) { if (array[i] < min) { min = array[i]; pos = i; } } return array[pos]; }
here propose solution using hashmap
:
public int getleastcommonnum(int[] array) { map<integer, integer> occurrences = new hashmap<integer, integer> (); (int num : array) { if (occurrences.containskey(num)) { occurrences.put(num, occurrences.get(num) + 1); } else { occurrences.put(num, 1); } } int minoccurred = -1; int minoccurredcnt = -1; (map.entry<integer, integer> occurrencesentry : occurrences.entryset()) { if (minoccurredcnt == -1 || minoccurredcnt > occurrencesentry.getvalue()) { minoccurredcnt = occurrencesentry.getvalue(); minoccurred = occurrencesentry.getkey(); } } return minoccurred ; }
i have coded heart, might have small spelling mistake.
Comments
Post a Comment