관리 메뉴

LC Studio

HackerRank Counting Sort 1 (JAVA) 본문

Java/HackerRank

HackerRank Counting Sort 1 (JAVA)

Leopard Cat 2022. 3. 29. 10:24

https://www.hackerrank.com/challenges/one-week-preparation-kit-countingsort1/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=preparation-kits&playlist_slugs%5B%5D=one-week-preparation-kit&playlist_slugs%5B%5D=one-week-day-two 

 

Counting Sort 1 | HackerRank

Count the number of times each value appears.

www.hackerrank.com

문제

Each of the resulting values result[i] represents the number of times appeared in.

ex)

Sample Input

100
63 25 73 1 98 73 56 84 86 57 16 83 8 25 81 56 9 53 98 67 99 12 83 89 80 91 39 86 76 85 74 39 25 90 59 10 94 32 44 3 89 30 27 79 46 96 27 32 18 21 92 69 81 40 40 34 68 78 24 87 42 69 23 41 78 22 6 90 99 89 50 30 20 1 43 3 70 95 33 46 44 9 69 48 33 60 65 16 82 67 61 32 21 79 75 75 13 87 70 33  

Sample Output

0 2 0 2 0 0 1 0 1 2 1 0 1 1 0 0 2 0 1 0 1 2 1 1 1 3 0 2 0 0 2 0 3 3 1 0 0 0 0 2 2 1 1 1 2 0 2 0 1 0 1 0 0 1 0 0 2 1 0 1 1 1 0 1 0 1 0 2 1 3 2 0 0 2 1 2 1 0 2 2 1 2 1 2 1 1 2 2 0 3 2 1 1 0 1 1 1 0 2 2 

 

문제를 간단히 요약하자면,

 

첫번째 줄에 n이 주어지고(100<n<100^6)

두번째 줄에 n개의 숫자가 주어진다.(숫자는 0이상 100미만)

출력은 result[] 0~100미만까지 각 숫자가 몇번 나왔는지 카운팅하여 출력하는 것이다.

 

바로 코드를 보겠다.

public static List<Integer> countingSort(List<Integer> arr) {
    // Write your code here
 
        int[] sol = new int[100]; //숫자의 개수를 기록할 배열선언

        for(int i=0;i<arr.size();i++){
            sol[arr.get(i)] = sol[arr.get(i)] + 1;
            //arr List의 각 자리값에 해당하는 sol배열의 자릿값을 찾아 +1을 해준다 
        }

        List<Integer> list = new ArrayList<>(); //List 선언
        for(int element : sol){ 
            list.add(element); //for문을 통해 sol의 각 요소를 list에 저장
        }
        return list;
    }

 복잡한 구조는 아니어서 주석을 보면 이해가 될것이다. 참고하시길!

 

 

반응형

'Java > HackerRank' 카테고리의 다른 글

HackerRank Time Convertion (JAVA)  (0) 2022.03.24