Count different values in array in Java

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

    Try this:

    import java.util.ArrayList;
    public class DifferentValues {
    
     public static void main(String[] args)
      {
        int[] a ={1, 2, 3, 1};
        System.out.println(differentValuesUnsorted(a));
      }
    
     public static int differentValuesUnsorted(int[] a)
     {
       ArrayList ArrUnique = new ArrayList();
       int values=0;      //values of different numbers
       for (int num : a) {
           if (!ArrUnique.contains(num)) ArrUnique.add(num);
       }
       values = ArrUnique.size();
       if (values == 1) values = 0;       
       return values;
     }
    }
    

    input:{1,1,1,1,1} - output: 0
    input:{1,2,3,1} - output: 3

提交回复
热议问题