Search code examples
javaarraysloopsreturnunique

Return the number of unique number values in the array "arr"


I am looking for a way to find the number of unique number values in an array.

I can't use imports for this project but I can use loops and conditional statements.

For instance the array

int[] arr1 = {3, -3, -1,  0, -1,  4,  0,  3,  4,  0};

should return 5

Here's what I came up with so far:

public static int countUniqueIntegers(int[] arr){
    
    // Initialize int "counter" with value 0
    int num_unique = 0;
    
    // TO DO: Add logic to count unique values
    if(arr.length == 0) return 0;
    if(arr.length == 1) return 1;
    double currentNumber = arr[0];
    int currentCount =1;
    for(int i =1; i < arr.length; i++)
    {
      if(arr[i] != currentNumber)
      {
        currentCount++;
        currentNumber = arr[i];
      }
    }
    // Return number of unique values
    return num_unique;
  }

Solution

  • We can start with an assumption that every value in array is unique. So number of unique values at the start is the same as array length. After this, we have to compare every value in the array with every other value in the same array. For this you need another "for" loop inside your "for" loop. If current item from outside (first) loop equals some item from inside loop, you just subtract 1 from your variable with unique numbers count (i.e. array length at the start).
    All you have to do now - programm it :)