본문 바로가기

Algorithms/11 Coding Interview (CS Dojo)

Most Frequently Occurring Item in an Array

Most Frequently Occurring Item in an Array (Java)

Find the most frequently occurring item in an array.

Example: The most frequently occurring item in [1, 3, 1, 3, 2, 1] is 1.

If you're given an empty array, you should return null (in Java) or None (in Python).

You can assume that there is always a single, unique value that appears most frequently unless the array is empty.  For instance, you won't be given an array such as [1, 1, 2, 2].


배열내 item 중에서 가장 많이 있는 item을 고르는 문제

HashMap이나 HashTable, or Dictionary 를 사용해서 하면 될 듯


HashMap과 HashTable의 차이

https://www.geeksforgeeks.org/differences-between-hashmap-and-hashtable-in-java/


HashTable과 Dictionary의 차이

https://www.codeproject.com/Tips/602537/Hashtable-vs-Dictionary


내가 푼 코드인데 확 깔끔하지는 않음

Big O =  O(n)


import java.util.HashMap;


public class MF {

    public static void main(String[] args) {

        // NOTE: The following input values are used for testing your solution.


        // mostFrequent(array1) should return 1.

        int[] array1 = {1, 3, 1, 3, 2, 1};

        // mostFrequent(array2) should return 3.

        int[] array2 = {3, 3, 1, 3, 2, 1};

        // mostFrequent(array3) should return null.

        int[] array3 = {};

        // mostFrequent(array4) should return 0.

        int[] array4 = {0};

        // mostFrequent(array5) should return -1.

        int[] array5 = {0, -1, 10, 10, -1, 10, -1, -1, -1, 1};

    }


    // Implement your solution below.

    public static Integer mostFreqent(int[] givenArray) {

        Integer maxItem = null;

        Integer arraySize = givenArray.length;

        Integer half = arraySize/2;

        if(arraySize == 0){

            return maxItem;

        }else if(arraySize == 1){

            maxItem = givenArray[0];

            return maxItem;

        }

        HashMap<Integer, Integer> map = new HashMap();

        for(int i = 0; i<arraySize; i++){

            if(map.containsKey(givenArray[i])){

               int count = map.get(givenArray[i]) + 1;

               map.put(givenArray[i], count);

                

               if (map.get(maxItem) < map.get(givenArray[i])){

                   maxItem = givenArray[i];

               }

                

               if(count >= half){

                  return maxItem;

               }

            } else {

                map.put(givenArray[i], 1);

                if (i == 0){

                    maxItem = givenArray[i];

                }

            }

        }

        return maxItem;

    }

}