Показать дубликаты массива типа «Число х повторяется х раз - PullRequest
0 голосов
/ 08 июня 2019

Как я могу изменить свой код, чтобы я мог получить только одно число и дублировать время из массива?

Я попробовал классический метод, но он показывает как «2 повторения 2 раза» x2 строки, «0 повторений 3 раза» x3 строки и т. Д., Когда я просто хочу только один раз »2 повторения 2 раза; 0 повторений 3 раза» и т.д.

import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
   int[] array = {2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7};
   Arrays.sort(array);

   for(int i=0;i<array.length;i++){
     int count = 0;
     for(int j=i+1;j<array.length;j++){
       if(array[i]==array[j] && i != j){
         count = count + 1;
         System.out.println("elements" + array[i] + " repeats" + count + " times);
       }
     }
   }
 }
}

Ответы [ 3 ]

2 голосов
/ 08 июня 2019

Поскольку массив отсортирован, ему нужен только один цикл:

public static void main(String[] args) {
    int[] array = {2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7};
    Arrays.sort(array);
    int index = 0;
    int counter = 1;
    while (index < array.length - 1) {
        if (array[index] == array[index + 1]) {
            counter++;
        } else {
            if (counter > 1) {
                System.out.println("element " + array[index] + " repeats " + counter + " times");
            }
            counter = 1;
        }
        index++;
    }
    if (counter > 1) {
        System.out.println("element " + array[index] + " repeats " + counter + " times");
    }
}

Сравнивает каждый элемент со следующим. Если они равны, счетчик увеличивается, если нет, если он больше 1, это означает, что были дубликаты, и он печатает строку:

"element " + array[index] + " repeats " + counter + " times"

Если он не больше 1, индекс увеличивается, а счетчик сбрасывается до 1.
То же самое с циклом for:

for (index = 0; index < array.length - 1; index++) {
    if (array[index] == array[index + 1]) {
        counter++;
    } else {
        if (counter > 1) {
            System.out.println("element " + array[index] + " repeats " + counter + " times");
        }
        counter = 1;
    }
}
0 голосов
/ 08 июня 2019

Если вы используете Java 8 или выше, вы можете сгруппировать элементы на карте по номеру в качестве ключа и сколько раз он появляется в качестве значения.После этого вы можете фильтровать и отображать только элементы, которые появляются более одного раза.

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Integer[] array = {2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7};

        Arrays.stream(array)
                .collect(Collectors.groupingBy(s -> s))
                .entrySet()
                .stream()
                .filter(e -> e.getValue().size() > 1)
                .forEach(e -> System.out.println("elements " + e.getKey() + " repeats " + e.getValue().size() + " times"));
    }
}
0 голосов
/ 08 июня 2019

Вот один из способов сделать это.

      int[] array = { 2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7
      };
      Arrays.sort(array);

      int count = 1;
      int v = array[0];
      for (int i = 1;i < array.length;) {
         while (i < array.length && v == array[i++]) {
            count++;
         }
         if (count > 1) {
            System.out.println(v + " occurs " + count + " times.");
         }
         v = array[i - 1];
         count = 1;
      }

Вот несколько дополнительных способов, которые не требуют сортировки.

   public static void method2() {
      int[] array = { 2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7
      };
      Map<Integer, Integer> map = new HashMap<>();
      for (int i : array) {
         // If the map contains the number, bump the count
         if (map.containsKey(i)) {
            int count = map.get(i)+1; // increment count
            map.put(i,count);        // put it back
         } else {
            map.put(i, 1);  // intialize count to 1
         }
      }
      // Now go thru the map and display only the numbers when the value is > 1
      for (Map.Entry<?,Integer>  e : map.entrySet()) {
         if (e.getValue() > 1) {
            System.out.println(e.getKey() + " occurs " + e.getValue() + " 
        times.");
         }
      }
   }

Следующий метод использует возможности Stream, начиная с Java 8.


   public static void method3() {
      int[] array = { 2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7
      };

      Arrays.stream(array)
            // Convert the integers to an Integer object.
            .boxed()
            // group the values into a Map<Integer, Integer> where the key is
            // the number
            // and the value is the count.
            .collect(Collectors.groupingBy(k -> k, Collectors.counting()))
            // grab the entry set of that map
            .entrySet()
            // convert it to a stream
            .stream()
            // filter for entrysets where the value > 1
            .filter(e -> e.getValue() > 1)
            // and forEach entry set that passes the filter, print out the
            // number and its count.
            .forEach(e -> System.out.println(
                  e.getKey() + " occurs " + e.getValue() + " times."));

   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...