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

前端 未结 10 1395
面向向阳花
面向向阳花 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:21

        int numbers[]={7,2,6,1,4,7,4,5,4,7,7,3, 1};
        String temp="";
        int count=0;
        Arrays.sort(numbers);
    
        for (int i = 0; i < numbers.length; i++) {
    
            boolean duplicate = false;
            for(int j = 0; j < numbers.length; j++) {
                if ((i != j) && numbers[i] == numbers[j]) {
                    duplicate = true;
                }
            }
    
            if (duplicate) {
                if(!temp.contains(""+numbers[i]))
                {
                temp+=numbers[i]+", ";//adding a number if its duplicate
                count++;//counting unique duplicate number
                }
                System.out.print(numbers[i] + " ");
            }
        }
        System.out.println("\nDuplicates are: "+temp+" count: "+count);
    

    Output:

     Duplicates are: 1, 4, 7,  count: 3
    

提交回复
热议问题