Java + Count duplicates from int array without using any Collection or another intermediate Array

前端 未结 10 1401
面向向阳花
面向向阳花 2020-12-06 02:50

As a part of the Java interview question paper I have got following issue to solve. But I am bit wonder whether how can I implement it without any Collection or intermediate

10条回答
  •  死守一世寂寞
    2020-12-06 03:26

    Agreed to Tim @tim-biegeleisen. Just minor change. Use the Arrays to sort the array.

    public class DuplicateClass {
    
        public static void main(String[] args) {
            int[] values = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
            duplicate(values);
        }
    
        public static void duplicate(int numbers[]) {
            Arrays.sort(numbers);
            int previous = numbers[0] - 1;
            ;
            int dupCount = 0;
    
            for (int i = 0; i < numbers.length; ++i) {
                if (numbers[i] == previous) {
                    ++dupCount;
                } else {
                    previous = numbers[i];
                }
            }
            System.out.println("There were " + dupCount + " duplicates in the array.");
        }
    }
    

提交回复
热议问题