Count different values in array in Java

后端 未结 9 1623
借酒劲吻你
借酒劲吻你 2021-02-10 17:15

I\'m writing a code where I have an int[a] and the method should return the number of unique values. Example: {1} = 0 different values, {3,3,3} = 0 different values, {1,2} = 2 d

9条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-10 17:49

    This is actually much simpler than most people have made it out to be, this method works perfectly fine:

    public static int diffValues(int[] numArray){
        int numOfDifferentVals = 0;
    
        ArrayList diffNum = new ArrayList<>();
    
        for(int i=0; i

    Let me walk you through it:

    1) Provide an int array as a parameter.

    2) Create an ArrayList which will hold integers:

    • If that arrayList DOES NOT contain the integer with in the array provided as a parameter, then add that element in the array parameter to the array list
    • If that arrayList DOES contain that element from the int array parameter, then do nothing. (DO NOT ADD THAT VALUE TO THE ARRAY LIST)

    N.B: This means that the ArrayList contains all the numbers in the int[], and removes the repeated numbers.

    3) The size of the ArrayList (which is analogous to the length property of an array) will be the number of different values in the array provided.


    Trial

    Input:

      int[] numbers = {3,1,2,2,2,5,2,1,9,7};
    

    Output: 6

提交回复
热议问题