자료구조 예제

개발하는 운동인·2025년 10월 19일

바로가기 사이트

https://school.programmers.co.kr/learn/challenges?tab=algorithm_practice_kit

딕셔너리

예제 1: 귤 고르기

using System;
using System.Linq;
using System.Collections.Generic;

public class Solution
{
    public int solution(int k, int[] tangerine)
    {
        int answer = 0;
        //[1,3,2,5,4,5,2,3] 
        //1 -> 1개
        //2 -> 2개
        //3 -> 2개
        //4 -> 1개
        //5 -> 2개 
        //k가 6이라면 6개까지 담을 수 있음. 
        // 1 ,2,3 까지 담을 수 있음. 
        Dictionary<int,int> newDic = new Dictionary<int,int>();
        
        for(int i =0; i < tangerine.Length; i++)
        {
            if(!newDic.ContainsKey(tangerine[i]))
            {
                newDic.Add(tangerine[i],1); //존재하지 않는다면 1로 설정 
            }
            else
            {
                newDic[tangerine[i]]++; //이미 값이 존재한다면 증가!
            }
        }
        
        List<int> keyList = new List<int>(newDic.Keys);
        keyList =  keyList.OrderByDescending(x => newDic[x]).ToList();
        //아래처럼 해도 됨.
        //keyList.Sort((a,b) => newDic[b].CompareTo(newDic[a]));
        //a와 b를 비교할건데, b가 a보다 크다면
        
        int sum = 0;
        
        foreach(var count in keyList)
        {
            sum += newDic[count];
            answer++;
            if(sum >= k)
            {
                break;
            }
        }
        return answer;
    }
}

코드 순서

스택과 큐

예제 1: 기능 개발

https://school.programmers.co.kr/learn/courses/30/lessons/42586?language=csharp

using System;
using System.Collections.Generic;

public class Solution {
    public int[] solution(int[] progresses, int[] speeds) 
    {
        int[] answer = new int[] {};
        
        Queue<int> queue = new Queue<int>();
            
        for(int i = 0; i < progresses.Length; i++)
        {
            int remain = 100 - progresses[i];
            
            int lastDay =  (int)Math.Ceiling((double)remain / speeds[i]); //올림. Math.Ceiling(Value); : Value 는 올림할 실수(double값), 리턴 타입은 double이다. 최종 계산하기 전에 int로 형 변환하여 lastDay의 형식과 맞춰야 함
            
            queue.Enqueue(lastDay);
            
        }
        
        List<int> result = new List<int>();
        
        while(queue.Count > 0 )
        {
            int standardDay =  queue.Dequeue();
            int count = 1; //무조건 1번은 배포하므로 순회할 때 1로 초기화.
            
            while(queue.Count > 0 && standardDay >= queue.Peek())
            {
                count++;
                queue.Dequeue();
            }
            result.Add(count);
        }
        
        answer = result.ToArray();
        return answer;
    }
}

알고리즘 동작 그림 예시


알고리즘 동작 코드 설명

    1. 먼저 각 기능에 대한 배포일을 구해서 해당 배포일을 큐에 저장. -> for문 참고
    1. queue.Dequeue()을 통해 첫번째 배포일을 기준으로 queue.Peek()을 이용해서 현재 큐에 저장된 배포일을 비교한다.
    1. 만약 첫번째 배포일이 더 크다면 count를 1씩 증가하고, queue.Dequeue()을 하여 큐에 데이터를 1개 뺀다.
    1. 최종 count값을 리스트< int > 에 추가.
    1. 1~4과정을 반복하여 큐에 데이터가 남아있을 때까지 실행.
    1. 리스트를 ToArray()하여 배열로 변환 후 answer 출력

예제 2 : 올바른 괄호

0개의 댓글