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

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

    I think, this is also a way to calculate it:

    public class App {
        public static void main(String[] args) {
            Integer[] intArr = { 7, 2, 6, 1, 4, 7, 4 };
            List listInt = Arrays.asList(intArr);
    
            Map map = new HashMap<>();
            Integer dupCount = 0;
            StringBuilder dupvalues = new StringBuilder();
    
            for (Integer integer : intArr) {
                int times = Collections.frequency(listInt, integer);
                if (map.containsKey(integer)) {
                    dupvalues.append(integer).append(",");
                    dupCount++;
                } else
                    map.put(integer, times);
            }
            System.out.println("There were " + dupCount + " duplicates in the array. The value are : "+dupvalues);
        }
    }
    

提交回复
热议问题