Count different values in array in Java

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

    First create distinct value array, It can simply create using HashSet.

    Then alreadyPresent.size() will provide number of different values. But for the case such as -{3,3,3} = 0 (array contains same elements); output of alreadyPresent.size() is 1. For that use this simple filter

    if(alreadyPresent.size() == 1)){
        return 0;
    }
    

    Following code will give the count of different values.

    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Set;
    
    public class Demo {
    
      public static void main(String[] args)
      {
           int array[] = {9,9,5,2,3};
           System.out.println(differentValuesUnsorted(array));
      }
    
      public static int differentValuesUnsorted(int[] array)
      {
    
         Set alreadyPresent = new HashSet();
    
         for (int nextElem : array) {
             alreadyPresent.add(nextElem);
         }
    
         if(alreadyPresent.size() == 1){
             return 0;
         }
    
         return alreadyPresent.size();
    
      }
    }
    

提交回复
热议问题