Count different values in array in Java

后端 未结 9 1655
借酒劲吻你
借酒劲吻你 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条回答
  •  旧时难觅i
    2021-02-10 17:57

    Use a set to remove duplicates

     public static int differentValuesUnsorted(int[] a) {
         if (a.length < 2) {
             return 0;
         }
    
         Set uniques = new HashSet<>(a);
         return singleUnique.size();
     }
    

提交回复
热议问题