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

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

    Below method not use any collection, just use Arrays.sort() method to help sort array into ascending order as default, e.g array = [9,3,9,3,9] will sort into [3,3,9,9,9].If input [9,9,9,9,9], expected result is 1, since only repeated number is 9.If input [9,3,9,3,9,255,255,1], expected result is 3, since repeated numbers are 3,9,255. If input [7,2,6,1,4,7,4,5,4,7,7,3,1], expected result is 3, since repeated numbers are 1,4,7.

    public static int findDuplicateCountsInArray(int[] nums) {
        // Sort the input array into default ascending order
        Arrays.sort(nums);
        int prev = nums[0];
        int count = 0;
        // Recording a number already a repeated one
        // e.g [9,9,9] the 3rd 9 will not increase duplicate count again
        boolean numAlreadyRepeated = false;
        for(int i = 1; i < nums.length; i++) {
            if(prev == nums[i] && !numAlreadyRepeated) {
                count++;
                numAlreadyRepeated = true;
            } else if(prev != nums[i]) {
                prev = nums[i];
                numAlreadyRepeated = false;
            }
        }
        return count;
    }
    

提交回复
热议问题