Count different values in array in Java

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

    You can use a HashSet, which can only contain unique elements. The HashSet will remove the duplicated items and you can then get the size of the set.

    public static int differentValuesUnsorted(int[] a) {
        Set unique = new HashSet();
        for (int val : a) {
            unique.add(val); // will only be added if a is not in unique
        }
        if (unique.size() < 2) { // if there are no different values
            return 0;
        }
        return unique.size();
    }
    

提交回复
热议问题