Count different values in array in Java

后端 未结 9 1624
借酒劲吻你
借酒劲吻你 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<Integer> list=new ArrayList<Integer>();   //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();
    }
    
    0 讨论(0)
  • 2021-02-10 17:57

    Use a set to remove duplicates

     public static int differentValuesUnsorted(int[] a) {
         if (a.length < 2) {
             return 0;
         }
    
         Set<Integer> uniques = new HashSet<>(a);
         return singleUnique.size();
     }
    
    0 讨论(0)
  • 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<Integer> alreadyPresent = new HashSet<Integer>();
    
         for (int nextElem : array) {
             alreadyPresent.add(nextElem);
         }
    
         if(alreadyPresent.size() == 1){
             return 0;
         }
    
         return alreadyPresent.size();
    
      }
    }
    
    0 讨论(0)
提交回复
热议问题