2013-08-10 3 views
-1

Как я могу обнаружить противоположность режима в java?Наименьшая общая целая java?

Например, если бы я хотел найти наименьшее общее число в массиве чисел, как бы я это сделал?

Спасибо.

Что я пробовал:

public int getLeastCommonNum(int[] array) 
{ 
int min = array[0]; 
int pos = 0; 
for (int i = 1; i < array.length; i++) 
{ 
    if (array[i] < min) 
    { 
    min = array[i]; 
    pos = i; 
    } 
} 
return array[pos]; 
} 
+0

Answered здесь: http://stackoverflow.com/questions/13618650/java-finding-the-least-common-integer-in -a-sorted-array – jrd1

+0

Я уже посмотрел туда, не очень помог. – Chase

+1

Хорошо, но __Что еще вы пробовали? __ – jrd1

ответ

1

Здесь я предлагаю решение с помощью HashMap:

public int getLeastCommonNum(int[] array) 
{ 
    Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>(); 
    for (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; 
    for (Map.Entry<Integer, Integer> occurrencesEntry : occurrences.entrySet()) { 
     if (minOccurredCnt == -1 || minOccurredCnt > occurrencesEntry.getValue()) { 
      minOccurredCnt = occurrencesEntry.getValue(); 
      minOccurred = occurrencesEntry.getKey(); 
     } 
    } 
    return minOccurred ; 
} 

Я кодированное все наизусть, так что может быть, что у меня есть некоторая небольшая Опечатка ,

+0

Может только перебирать массив или экземпляр java.lang.Iterable @'хождения 'для (Map.Entry хожденияEntry: события) { – Chase

+0

@Chase Спасибо, исправлено. –

+0

Отредактировано для изменения 'contains()' to 'containsKey()' –

0

на основе Boris Strandjev версии, но с использованием Multiset для подсчета:

@Nullable 
public Integer getLeastCommonNumV2(final int[] array) 
{ 
    // step 1: count 
    final Multiset<Integer> occurances = HashMultiset.create(); 
    for (final int num : array) { 
     occurances.add(num); 
    } 

    // step 2: find least common 
    Multiset.Entry<Integer> leastCommon = null; 
    for (final Multiset.Entry<Integer> occurance : occurances.entrySet()) { 
     if (leastCommon == null || occurance.getCount() < leastCommon.getCount()) { 
      leastCommon = occurance; 
     } 
    } 
    return leastCommon == null ? null : leastCommon.getElement(); 
} 
Смежные вопросы