Count different values in array in Java

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

    For small arrays, this is a fast concise method that does not require the allocation of any additional temporary objects:

    public static int uniqueValues(int[] ids) {
        int uniques = 0;
    
        top:
        for (int i = 0; i < ids.length; i++) {
            final int id = ids[i];
            for (int j = i + 1; j < ids.length; j++) {
                if (id == ids[j]) continue top;
            }
            uniques++;
        }
        return uniques;
    }
    

提交回复
热议问题