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

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

    This is the simplest solution I can think of. I just added an extra counter so that integers with two or more repetitions still in the array are ignored.

    static int findNumber(int[] arr) 
    {  
        int duplicateCounter = 0;
    
        System.out.print("Duplicates: ");
    
        for(int i = 0; i < arr.length; i++)
        {
            boolean duplicate = false;
            int numOfOccurrences = 1;
    
            for (int j = (i+1); j < arr.length; j++)
            {
                if (arr[i] == arr[j])
                {
                    numOfOccurrences++;
                    duplicate = true;
                }
            }
            if(numOfOccurrences == 2 && duplicate == true)
            {
                duplicateCounter++;
                System.out.print(arr[i] + " ");
            }
        }
    
        return duplicateCounter;
    }
    

    My test run: Test run

    Input: 1, 2, 3, 4, 2, 4, 1, 1, 1

    Duplicates: 2 4 1

    Number of duplicates: 3

提交回复
热议问题