Task: to find the number of different elements in the array. The first method works correctly, the second one does not work. Tell me, what's the reason? The second method looks simpler and more common option of counting.

int []arr = {3, 3, 5, 5, 5, 6, 7, 8, 8, 97}; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length-1; j++) { if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } //первый способ int uniqueNumber = arr.length; // создаём переменную с начальным значение, равным размеру массива (предолагаем, что все уникальны значения) for(int i=1;i<arr.length;i++){ // пробегаемся по массиву if(arr[i-1]==arr[i]) uniqueNumber--; // если смежные элементы равны, то значение uniqueNumber уменьшаем на единицу } System.out.println(); System.out.println(uniqueNumber); //второй способ int count = 0; for (int i = 0; i < arr.length; i++) { if(arr[i]!=arr[i+1]) count++; } System.out.println(); System.out.println(count); 
  • one
    Integer [] arr = {3, 3, 5, 5, 5, 6, 7, 8, 8, 97}; Set <Integer> mySet = new HashSet (Arrays.asList (arr)); System.out.println (mySet.size ()); - DimXenon

2 answers 2

You do not take into account the first element, the score must be with one, or if the first two different elements are found, the counter must be increased by 2. Plus the cycle must be before the arr.length-1 element, otherwise you will get an ArrayIndexOutOfBoundsException error as the element and the arr.length index in the array it can not be.

  int count = 1; for (int i = 0; i < arr.length-1; i++) { if(arr[i]!=arr[i+1]) { count++; } } 

And you can still do with the Set collection for example like this:

 Set<Integer> uniqueElements = new HashSet<>(Arrays.stream(arr) .boxed().collect(Collectors.toList())); System.out.println(uniqueElements.size()); 
  • I'm still behind TreeSet - Vartlok
  • @Vartlok, why? After all, adding to HashSet is faster. - Mikhailov Valentine
  • will work faster - Vartlok
  • one
    @Vartlok, in HashSet, it seems like adding in constant time happens while in TreeSet for log (n). - Mikhailov Valentine
  • In theory, but in reality there is a sheet (on the account of ArreyList was wrong) in each basket and everything turns into N / quantity_cash - Vartlok
 int[] arr = {3, 3, 5, 5, 5, 6, 7, 8, 8, 97}; List<Integer> tmp = new ArrayList<Integer>(); for (int i = 0; i < arr.length; i++) { if (!tmp.contains(arr[i])) { tmp.add(arr[i]); } } System.out.println(tmp.size()); // 6 {3, 5, 6, 7, 8, 97} 
  • one
    Then it's better to use Set and TreeSet - Vartlok
  • Thanks for the solution. - Klim