Подтвердить что ты не робот

Найти самый популярный элемент в массиве int []

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};

как я могу написать метод и вернуть 7?

Я хочу сохранить его родным без помощи списков, карт или других помощников. Только массивы [].

4b9b3361

Ответ 1

public int getPopularElement(int[] a)
{
  int count = 1, tempCount;
  int popular = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > count)
    {
      popular = temp;
      count = tempCount;
    }
  }
  return popular;
}

Ответ 2

Попробуйте этот ответ. Во-первых, данные:

int[] a = {1,2,3,4,5,6,7,7,7,7};

Здесь мы строим карту, подсчитывающую количество раз, когда появляется каждое число:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
    Integer count = map.get(i);
    map.put(i, count != null ? count+1 : 0);
}

Теперь мы найдем число с максимальной частотой и вернем его:

Integer popular = Collections.max(map.entrySet(),
    new Comparator<Map.Entry<Integer, Integer>>() {
    @Override
    public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}).getKey();

Как вы можете видеть, самым популярным номером является семь:

System.out.println(popular);
> 7

ИЗМЕНИТЬ

Здесь мой ответ без использования карт, списков и т.д. и использование только массивов; хотя я сортирую массив на месте. Это O (n log n) сложность, лучше, чем принятое решение O (n ^ 2).

public int findPopular(int[] a) {

    if (a == null || a.length == 0)
        return 0;

    Arrays.sort(a);

    int previous = a[0];
    int popular = a[0];
    int count = 1;
    int maxCount = 1;

    for (int i = 1; i < a.length; i++) {
        if (a[i] == previous)
            count++;
        else {
            if (count > maxCount) {
                popular = a[i-1];
                maxCount = count;
            }
            previous = a[i];
            count = 1;
        }
    }

    return count > maxCount ? a[a.length-1] : popular;

}

Ответ 3

  • Возьмите карту в элемент map → count
  • Итерация через массив и обработка карты
  • Итерации по карте и узнайте популярные

Ответ 4

Предполагая, что ваш массив отсортирован (например, тот, который вы опубликовали), вы можете просто перебирать массив и считать самый длинный сегмент элементов, это что-то вроде @narek.gevorgyan post, но без ужасно большого массива, и он использует тот же объем памяти независимо от размера массива:

private static int getMostPopularElement(int[] a){
    int counter = 0, curr, maxvalue, maxcounter = -1;
    maxvalue = curr = a[0];

    for (int e : a){
        if (curr == e){
            counter++;
        } else {
            if (counter > maxcounter){
                maxcounter = counter;
                maxvalue = curr;
            }
            counter = 0;
            curr = e;
        }
    }
    if (counter > maxcounter){
        maxvalue = curr;
    }

    return maxvalue;
}


public static void main(String[] args) {
    System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}

Если массив не отсортирован, сортируйте его с помощью Arrays.sort(a);

Ответ 5

Использование потоковJava 8

int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
    .boxed()
    .collect(Collectors.groupingBy(Function.identity(), counting()));

int max = count.entrySet().stream()
    .max((first, second) -> {
        return (int) (first.getValue() - second.getValue());
    })
    .get().getKey();

System.out.println(max);

Объяснение

Мы конвертируем массив int[] data в целочисленный поток в штучной упаковке. Затем мы собираем groupingBy на элементе и используем вторичный счетный коллектор для подсчета после groupBy.

Наконец, мы снова сортируем карту количества элементов -> на основе количества, используя компаратор потока и лямбда-выражения.

Ответ 6

Это без карт:

public class Main {       

    public static void main(String[] args) {
        int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
        System.out.println(getMostPopularElement(a));        
    }

    private static int getMostPopularElement(int[] a) {             
        int maxElementIndex = getArrayMaximumElementIndex(a); 
        int[] b = new int[a[maxElementIndex] + 1]

        for (int i = 0; i < a.length; i++) {
            ++b[a[i]];
        }

        return getArrayMaximumElementIndex(b);
    }

    private static int getArrayMaximumElementIndex(int[] a) {
        int maxElementIndex = 0;

        for (int i = 1; i < a.length; i++) {
            if (a[i] >= a[maxElementIndex]) {
                maxElementIndex = i;
            }
        }

        return maxElementIndex;
    }      

}

Вам нужно всего лишь изменить некоторый код, если в вашем массиве могут быть элементы < 0. И этот алгоритм полезен, когда ваши элементы массива не большие числа.

Ответ 7

Если вы не хотите использовать карту, просто выполните следующие действия:

  • Сортировка массива (с помощью Arrays.sort())
  • Используйте переменную для хранения наиболее популярного элемента (mostPopular), переменной для хранения своего количества вхождений в массиве (mostPopularCount) и переменной для хранения количества вхождений текущего числа в итерации (currentCount)
  • Итерации через массив. Если текущий элемент совпадает с mostPopular, увеличьте currentCount. Если нет, reset currentCount до 1. Если currentCount является > mostPopularCount, установите mostPopularCount в currentCount и mostPopular для текущего элемента.

Ответ 8

Значение элемента массива должно быть меньше длины массива для этого:

public void findCounts(int[] arr, int n) {
    int i = 0;

    while (i < n) {
        if (arr[i] <= 0) {
            i++;
            continue;
        }

        int elementIndex = arr[i] - 1;

        if (arr[elementIndex] > 0) {
            arr[i] = arr[elementIndex];
            arr[elementIndex] = -1;
        }
        else {
            arr[elementIndex]--;
            arr[i] = 0;
            i++;
        }
    }

    Console.WriteLine("Below are counts of all elements");

    for (int j = 0; j < n; j++) {
        Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
    }
}

Сложность по времени будет O(N), а сложность пространства - O(1).

Ответ 9

Похоже, вы ищете значение режима (статистический режим), посмотрите Apache Docs для статистических функций.

Ответ 10

import java.util.Scanner;


public class Mostrepeatednumber
{
    public static void main(String args[])
    {
        int most = 0;
        int temp=0;
        int count=0,tempcount;
        Scanner in=new Scanner(System.in);
        System.out.println("Enter any number");
        int n=in.nextInt();
        int arr[]=new int[n];
        System.out.print("Enter array value:");
        for(int i=0;i<=n-1;i++)
        {
            int n1=in.nextInt();
            arr[i]=n1;
        }
        //!!!!!!!! user input concept closed
        //logic can be started
        for(int j=0;j<=n-1;j++)
        {
        temp=arr[j];
        tempcount=0;
            for(int k=1;k<=n-1;k++)
                {
                if(temp==arr[k])
                    {
                        tempcount++;
                    }   
                        if(count<tempcount)
                            {
                                most=arr[k];
                                    count=tempcount;
                            }
                }

        }
        System.out.println(most);
    }

}

Ответ 11

package frequent;

import java.util.HashMap;
import java.util.Map;

public class Frequent_number {

    //Find the most frequent integer in an array

    public static void main(String[] args) {
        int arr[]= {1,2,3,4,3,2,2,3,3};

        System.out.println(getFrequent(arr));
        System.out.println(getFrequentBySorting(arr));
    }

    //Using Map , TC: O(n)  SC: O(n)
    static public int getFrequent(int arr[]){
        int ans=0;
        Map<Integer,Integer> m = new HashMap<>();
        for(int i:arr){
            if(m.containsKey(i)){
                m.put(i, m.get(i)+1);
            }else{
                m.put(i, 1);
            }
        }
        int maxVal=0;
        for(Integer in: m.keySet()){
            if(m.get(in)>maxVal){
                ans=in;
                maxVal = m.get(in);
            }
        }
        return ans;
    }

    //Sort the array and then find it TC: O(nlogn) SC: O(1)
    public static int getFrequentBySorting(int arr[]){
        int current=arr[0];
        int ansCount=0;
        int tempCount=0;
        int ans=current;
        for(int i:arr){
            if(i==current){
                tempCount++;
            }
            if(tempCount>ansCount){
                ansCount=tempCount;
                ans=i;
            }
            current=i;
        }
        return ans;
    }

}

Ответ 12

Mine Linear O (N)

Использование карты для сохранения всех элементов differents, найденных в массиве, и сохранения количества раз, а затем просто получения max с карты.

import java.util.HashMap;
import java.util.Map;

public class MosftOftenNumber {

    // for O(N) + map O(1) = O(N) 
    public static int mostOftenNumber(int[] a)
    {
        Map m = new HashMap<Integer,Integer>();
        int max = 0;
        int element = 0;

        for(int i=0; i<a.length; i++){
            //initializing value for the map the value will have the counter of each element
            //first time one new number its found will be initialize with zero 
            if (m.get(a[i]) == null)
                m.put(a[i],0);

            //save each value from the array and increment the count each time its found
            m.put(a[i] , (int)m.get(a[i]) + 1);

            //check the value from each element and comparing with max
            if ((int)m.get(a[i])>max){
                max = (int) m.get(a[i]);
                element = a[i];
            }

        }
        return element;
    }

    public static void main(String args[]) {
//      int[] array = {1,1,2,1,1};
//      int[] array = {2,2,1,2,2};
        int[] array = {2,2,1,3,3,5,5,6,6,7,7,9,9,10,10,10,10,11,12,13,14,15,15,1,15,15,1,15,15};
        System.out.println(mostOftenNumber(array));
    }


}

Ответ 13

Наилучшим подходом будет использование карты, где ключ будет элементом, а значением будет отсчет каждого элемента. Наряду с этим сохраняем массив размеров, который будет содержать индекс самого популярного элемента. Заполните этот массив при построении самой карты, чтобы нам снова не пришлось перебирать карту.

Подход 2: -

Если кто-то хочет пойти с двумя циклами, вот импровизация из принятого ответа, где нам не нужно начинать второй цикл с каждого раза каждый раз

public class TestPopularElements {
    public static int getPopularElement(int[] a) {
        int count = 1, tempCount;
        int popular = a[0];
        int temp = 0;
        for (int i = 0; i < (a.length - 1); i++) {
            temp = a[i];
            tempCount = 0;
            for (int j = i+1; j < a.length; j++) {
                if (temp == a[j])
                    tempCount++;
            }
            if (tempCount > count) {
                popular = temp;
                count = tempCount;
            }
        }
        return popular;
    }

    public static void main(String[] args) {
        int a[] = new int[] {1,2,3,4,5,6,2,7,7,7};

        System.out.println("count is " +getPopularElement(a));
    }

}

Ответ 14

Предполагая, что ваш массив int отсортирован, я бы сделал...

int count = 0, occur = 0, high = 0, a;

for (a = 1; a < n.length; a++) {
    if (n[a - 1] == n[a]) {
       count++;
       if (count > occur) {
           occur = count;
           high = n[a];
       }
     } else {
        count = 0;
     }
}
System.out.println("highest occurence = " + high);

Ответ 15

public static void main(String[] args) {

    int[] myArray = {1,5,4,4,22,4,9,4,4,8};
    Map<Integer,Integer> arrayCounts = new HashMap<>();
    Integer popularCount  = 0;
    Integer popularValue = 0;

    for(int i = 0; i < myArray.length; i++) {
        Integer count = arrayCounts.get(myArray[i]);
        if (count == null) {
            count = 0;
        }
        arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
        if (count > popularCount) {
            popularCount = count;
            popularValue = myArray[i];
        }
    }

    System.out.println(popularValue + " --> " + popularCount);
}

Ответ 16

ниже код может быть помещен в основной метод

    // TODO Auto-generated method stub
    Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
    Set<Integer> set = new HashSet<Integer>(list);
    int highestSeq = 0;
    int seq = 0;
    for (int i : set) {
        int tempCount = 0;
        for (int l : list) {
            if (i == l) {
                tempCount = tempCount + 1;
            }
            if (tempCount > highestSeq) {
                highestSeq = tempCount;
                seq = i;
            }
        }

    }

    System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);

Ответ 17

public class MostFrequentIntegerInAnArray {

    public static void main(String[] args) {
        int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
        System.out.println("Most common item = "+getMostFrequentInt(items));
    }

    //Time Complexity = O(N)
    //Space Complexity = O(N)
    public static int getMostFrequentInt(int[] items){
        Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
        for(int item : items){
            if(!itemsMap.containsKey(item))
                itemsMap.put(item, 1);
            else
                itemsMap.put(item, itemsMap.get(item)+1);
        }

        int maxCount = Integer.MIN_VALUE;
        for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
            if(entry.getValue() > maxCount)
                maxCount = entry.getValue();
        }
        return maxCount;
    }
}

Ответ 18

int largest = 0;
int k = 0;
for (int i = 0; i < n; i++) {
    int count = 1;
    for (int j = i + 1; j < n; j++) {
        if (a[i] == a[j]) {
            count++;
        }
    }
    if (count > largest) {
        k = a[i];
        largest = count;
    }
}

Итак, здесь n - длина массива, а a[] - ваш массив.

Сначала возьмите первый элемент и проверьте, сколько раз он повторяется, и увеличьте счетчик (count), чтобы увидеть, сколько раз он встречается. Убедитесь, что это максимальное количество раз, которое число до сих пор встречалось, если да, затем измените самую большую переменную (чтобы сохранить максимальное количество повторений), и если вы хотите также сохранить переменную, вы можете сделать это в другой переменной (здесь k).

Я знаю, что это не самый быстрый, но, безусловно, самый простой способ понять,

Ответ 19

public static int getMostCommonElement(int[] array) {

    Arrays.sort(array);

    int frequency = 1;
    int biggestFrequency = 1;
    int mostCommonElement = 0;

    for(int i=0; i<array.length-1; i++) {
        frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
        if(frequency>biggestFrequency) {
            biggestFrequency = frequency; 
            mostCommonElement = array[i];
        }
    }

    return mostCommonElement;
}

Ответ 20

import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
    public static void main(String [] args){
    int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
    Map map = new HashMap<Integer, Integer>();
    for(int i = 0 ; i < arrayToCheckFrom.length; i++){
    int sum = 0;
      for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
          if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
          sum += 1; 
      }
      map.put(arrayToCheckFrom[i], sum);
    }
    System.out.println(getMaxValue(map));
}
  public static Integer getMaxValue( Map<Integer,Integer> map){
        Map.Entry<Integer,Integer> maxEntry = null;
        Iterator iterator = map.entrySet().iterator();  
        while(iterator.hasNext()){
            Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
            if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
                maxEntry = pair; 
            } 
        }
        return maxEntry.getKey();
    }
}

Ответ 21

Этот метод возвращает массив со всеми популярными элементами, если существует более одного с таким же количеством повторений:

    private static int[] FindMostPopularElements(int[] inArray)
    {
        var result = new List<int>();

        var numbersAndTimes = inArray
            .GroupBy(g => g)
            .Select(x => new
            {
                number = x.Key,
                times = x.Count()
            })
            .OrderByDescending(o => o.times);

        int maxTimes = 0;
        foreach (var pair in numbersAndTimes)
        {
            if (pair.times >= maxTimes)
            {
                maxTimes = pair.times;
                result.Add(pair.number);

                //Console.WriteLine($"{pair.number} - Occurrences: {pair.times}");
            }
            else
            {
                break;
            }
        }

        return result.ToArray();
    }

Ответ 22

public class MostFrequentNumber {

    public MostFrequentNumber() {

    }

    int frequentNumber(List<Integer> list){

        int popular = 0;
        int holder = 0;

        for(Integer number: list) {
            int freq = Collections.frequency(list,number);

            if(holder < freq){
                holder = freq;
                popular = number;
            }
        }

       return popular;

    }

    public static void main(String[] args){

        int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};

        List<Integer> list = new ArrayList<Integer>();

        for(Integer num : numbers){
            list.add(num);
        }


        MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();

        System.out.println(mostFrequentNumber.frequentNumber(list));


    }
}

Ответ 23

Надеюсь, это поможет. публичный класс Ideone {   public static void main (String [] args) throws java.lang.Exception {

    int[] a = {1,2,3,4,5,6,7,7,7};
    int len = a.length;

    System.out.println(len);


    for (int i = 0; i <= len - 1; i++) {

        while (a[i] == a[i + 1]) {
            System.out.println(a[i]);

            break;
        }


    }


}

}

Ответ 24

Вы можете сосчитать вхождения разных чисел, а затем найти самое высокое. Это пример, в котором используется карта, но его относительно легко адаптировать к собственным массивам.

Второй по величине элемент: Давайте возьмем пример: [1,5,4,2,3] в этом случае, Вторым по величине элементом будет 4.

  1. Сортируйте массив в порядке убывания, как только результат сортировки будет выполнен A = [5,4,3,2,1]

  2. Получить второй по величине элемент из отсортированного массива, используя индекс 1. A [1] → который даст второй по величине элемент 4.

private static int getMostOccuringElement (int [] A) {       Карта occuringMap = new HashMap();

    //count occurences
    for (int i = 0; i < A.length; i++) { 
        if (occuringMap.get(A[i]) != null) {
            int val = occuringMap.get(A[i]) + 1;
            occuringMap.put(A[i], val);
        } else {
            occuringMap.put(A[i], 1);
        }
    }

    //find maximum occurence
    int max = Integer.MIN_VALUE; 
    int element = -1;
    for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
        if (entry.getValue() > max) {
            max = entry.getValue();
            element = entry.getKey();
        }
    }
    return element;
}

Ответ 25

Это неправильный синтаксис. Когда вы создаете анонимный массив, вы НЕ ДОЛЖНЫ указывать его размер.

Когда вы пишете следующий код:

    new int[] {1,23,4,4,5,5,5};

Здесь вы создаете анонимный массив int, размер которого будет определяться количеством значений, которые вы предоставляете в фигурных скобках.

Вы можете назначить эту ссылку, как вы это сделали, но это будет правильный синтаксис для этого: -

    int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};

Теперь просто Sysout с правильной позицией индекса:

    System.out.println(a[7]);