Back-end/Algorithm

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ชจ์˜๊ณ ์‚ฌ (java) - ์™„์ „ํƒ์ƒ‰

Nellie Kim 2023. 8. 16. 10:48
728x90

๐Ÿ’‍โ™€๏ธ  ๋ฌธ์ œ ์„ค๋ช…

์ˆ˜ํฌ์ž๋Š” ์ˆ˜ํ•™์„ ํฌ๊ธฐํ•œ ์‚ฌ๋žŒ์˜ ์ค€๋ง์ž…๋‹ˆ๋‹ค. ์ˆ˜ํฌ์ž ์‚ผ์ธ๋ฐฉ์€ ๋ชจ์˜๊ณ ์‚ฌ์— ์ˆ˜ํ•™ ๋ฌธ์ œ๋ฅผ ์ „๋ถ€ ์ฐ์œผ๋ ค ํ•ฉ๋‹ˆ๋‹ค. ์ˆ˜ํฌ์ž๋Š” 1๋ฒˆ ๋ฌธ์ œ๋ถ€ํ„ฐ ๋งˆ์ง€๋ง‰ ๋ฌธ์ œ๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ฐ์Šต๋‹ˆ๋‹ค.

1๋ฒˆ ์ˆ˜ํฌ์ž๊ฐ€ ์ฐ๋Š” ๋ฐฉ์‹: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2๋ฒˆ ์ˆ˜ํฌ์ž๊ฐ€ ์ฐ๋Š” ๋ฐฉ์‹: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
3๋ฒˆ ์ˆ˜ํฌ์ž๊ฐ€ ์ฐ๋Š” ๋ฐฉ์‹: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...

1๋ฒˆ ๋ฌธ์ œ๋ถ€ํ„ฐ ๋งˆ์ง€๋ง‰ ๋ฌธ์ œ๊นŒ์ง€์˜ ์ •๋‹ต์ด ์ˆœ์„œ๋Œ€๋กœ ๋“ค์€ ๋ฐฐ์—ด answers๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ฐ€์žฅ ๋งŽ์€ ๋ฌธ์ œ๋ฅผ ๋งžํžŒ ์‚ฌ๋žŒ์ด ๋ˆ„๊ตฌ์ธ์ง€ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.


โŒ ์ œํ•œ์‚ฌํ•ญ

  • ์‹œํ—˜์€ ์ตœ๋Œ€ 10,000 ๋ฌธ์ œ๋กœ ๊ตฌ์„ฑ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.
  • ๋ฌธ์ œ์˜ ์ •๋‹ต์€ 1, 2, 3, 4, 5์ค‘ ํ•˜๋‚˜์ž…๋‹ˆ๋‹ค.
  • ๊ฐ€์žฅ ๋†’์€ ์ ์ˆ˜๋ฅผ ๋ฐ›์€ ์‚ฌ๋žŒ์ด ์—ฌ๋Ÿฟ์ผ ๊ฒฝ์šฐ, returnํ•˜๋Š” ๊ฐ’์„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

 

 

๐Ÿ’ก  ์ž…์ถœ๋ ฅ ์˜ˆ

 

 

์ž…์ถœ๋ ฅ ์˜ˆ #1

  • ์ˆ˜ํฌ์ž 1์€ ๋ชจ๋“  ๋ฌธ์ œ๋ฅผ ๋งžํ˜”์Šต๋‹ˆ๋‹ค.
  • ์ˆ˜ํฌ์ž 2๋Š” ๋ชจ๋“  ๋ฌธ์ œ๋ฅผ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค.
  • ์ˆ˜ํฌ์ž 3์€ ๋ชจ๋“  ๋ฌธ์ œ๋ฅผ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๊ฐ€์žฅ ๋ฌธ์ œ๋ฅผ ๋งŽ์ด ๋งžํžŒ ์‚ฌ๋žŒ์€ ์ˆ˜ํฌ์ž 1์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ #2

  • ๋ชจ๋“  ์‚ฌ๋žŒ์ด 2๋ฌธ์ œ์”ฉ์„ ๋งž์ท„์Šต๋‹ˆ๋‹ค.

 

๐Ÿ‘ฉ ๋‚ด ํ’€์ด

import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        int[] first = {1,2,3,4,5}; // 5๊ฐœ์”ฉ ๋ฐ˜๋ณต
        int[] second = {2,1,2,3,2,4,2,5}; // 8๊ฐœ์”ฉ ๋ฐ˜๋ณต
        int[] third = {3,3,1,1,2,2,4,4,5,5}; // 10๊ฐœ์”ฉ ๋ฐ˜๋ณต
        int[] score = {0,0,0}; // ๊ฐ ์ˆ˜ํฌ์ž๋“ค์˜ ์ ์ˆ˜

        // ์ˆ˜ํฌ์ž๋“ค์˜ ์ ์ˆ˜ ๊ณ„์‚ฐ
        for(int i=0; i<answers.length; i++) {
            if(answers[i] == first[i%5]) score[0]++;
            if(answers[i] == second[i%8]) score[1]++;
            if(answers[i] == third[i%10]) score[2]++;
        }

        // ์ตœ๋Œ€ ์ ์ˆ˜ ๊ตฌํ•˜๊ธฐ
        int max = Math.max(score[0], Math.max(score[1], score[2]));

        // ์ตœ๋Œ€ ์ ์ˆ˜๋ฅผ ๊ฐ€์ง„ ์ˆ˜ํฌ์ž ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
        List<Integer> answerList = new ArrayList<Integer>();
        for(int i=0; i<score.length; i++) if(max == score[i]) answerList.add(i+1);

        // ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‹ค์‹œ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
        int[] answer = new int[answerList.size()];
        for(int i=0; i<answerList.size(); i++){
            answer[i] = answerList.get(i);
        }

        return answer;
    }
}

Max๋ฅผ ์ด์ค‘์œผ๋กœ ์‚ฌ์šฉํ•ด์„œ ์ตœ๋Œ€ ์ ์ˆ˜๋ฅผ ๊ตฌํ–ˆ๋‹ค.

 

๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•˜๊ณ , ๋‹ค์‹œ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ–ˆ๋‹ค.