728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ๐Ÿ˜ต‍๐Ÿ’ซ

https://school.programmers.co.kr/learn/courses/30/lessons/42840

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

 

๋‚ด ํ’€๐Ÿฆท

import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        // ์ˆ˜ํฌ์ž๋“ค์˜ ํŒจํ„ด ์ •์˜
        int[] pattern1 = {1, 2, 3, 4, 5};
        int[] pattern2 = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] pattern3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
        
        // ์ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•  ๋ฐฐ์—ด
        int[] scores = new int[3];
        
        // ๊ฐ ๋ฌธ์ œ์— ๋Œ€ํ•ด ์ˆ˜ํฌ์ž๋“ค์˜ ๋‹ต์•ˆ์„ ๋น„๊ตํ•˜์—ฌ ์ ์ˆ˜ ๊ณ„์‚ฐ
        for(int i = 0; i < answers.length; i++) {
            if(answers[i] == pattern1[i % pattern1.length]) {
                scores[0]++;
            }
            if(answers[i] == pattern2[i % pattern2.length]) {
                scores[1]++;
            }
            if(answers[i] == pattern3[i % pattern3.length]) {
                scores[2]++;
            }
        }
        
        // ์ œ์ผ ๋†’์€ ์ ์ˆ˜๋ฅผ ์ฐพ์Œ
        int maxScore = Math.max(scores[0], Math.max(scores[1], scores[2]));
        
        // ๊ฐ€์žฅ ๋†’์€ ์ ์ˆ˜๋ฅผ ๋ฐ›์€ ์ˆ˜ํฌ์ž๋ฅผ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
        List<Integer> result = new ArrayList<>();
        for(int i = 0; i < scores.length; i++) {
            if(scores[i] == maxScore) {
                result.add(i+1);
            }
        }
        
        return result.stream().mapToInt(i -> i).toArray();
    }
}

 

๊ฐ€์žฅ ๋งŽ์€ ์ ์ˆ˜๋ฅผ ํš๋“ํ•œ ์‚ฌ๋žŒ์„ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์˜€๋‹ค!!

๋‹ด๋Š”๊ฒƒ ๊นŒ์ง€๋Š” ์ •๋ง ์‰ฌ์šด๋ฐ return ๋ฌธ ์ž‘์„ฑํ•˜๋Š” ๊ณผ์ •์—์„œ ์–ด๋ ค์›€์ด ์žˆ์—ˆ๋‹ค!

 

์ฐธ๊ณ ํ•˜๋ฉด ์ข‹์„ ๊ฐœ๋…๋“ค โœ๏ธ

  • .stream()
    • stream : ๋ฐ์ดํ„ฐ ์ปฌ๋ ‰์…˜์˜ ์ถ”์ƒํ™”๋กœ, ์š”์†Œ๋“ค์„ ์ฐจ๋ก€์ฐจ๋ก€ ๊บผ๋‚ด ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” "๋ฐ์ดํ„ฐ ํ๋ฆ„" 
    • List<Integer> ๊ฐ์ฒด์—์„œ ๊ฐ ์š”์†Œ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์ŠคํŠธ๋ฆผ์„ ์ƒ์„ฑํ•œ๋‹ค 
    • ์ŠคํŠธ๋ฆผ์€ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ์ž‘์—…์„ ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ฃผ๋Š” ์ถ”์ƒํ™” ๋„๊ตฌ์ด๋‹ค
  • .mapToInt(i -> i) 
    • ์ŠคํŠธ๋ฆผ์˜ ๊ฐ ์š”์†Œ๋ฅผ ์ •์ˆ˜๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค
    • i -> i๋Š” ๋žŒ๋‹ค ํ‘œํ˜„์‹์œผ๋กœ, ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ ์š”์†Œ๋ฅผ i ๊ทธ๋Œ€๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค
    • ์ด ๊ณผ์ •์—์„œ ๊ฐ์ฒด(Integer)๋ฅผ ์›์‹œ ํƒ€์ž…(int)์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ฒŒ ๋œ๋‹ค
  • .toArray() 
    • ์ŠคํŠธ๋ฆผ์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค
    • ์ตœ์ข…์ ์œผ๋กœ List<Integer> ๊ฐ€ int[] ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜๋œ๋‹ค
728x90
๋ฐ˜์‘ํ˜•

+ Recent posts