Count different values in array in Java

后端 未结 9 1656
借酒劲吻你
借酒劲吻你 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:57

    Try this simple code snippet.

    public static int differentValuesUnsorted(int[] a)
    {
        ArrayList list=new ArrayList();   //import java.util.*;
        for(int i:numbers)                                  //Iterate through all the elements
          if(!list.contains(i))                             //checking for duplicate element
            list.add(i);                                    //Add to list if unique
        return list.size();
    }
    

提交回复
热议问题