Dictionary는 키와 값 쌍을 저장하는 컬렉션이다. 다른 언어에서는 '해시맵', '해시 테이블', '맵' 등으로 불리는 자료구조와 같다. Dictionary는 키를 사용하여 빠르게 데이터를 검색할 수 있도록 설계되어 있다.

Dictionary<TKey, TValue>는 두 개의 타입 매개변수를 사용한다

TKey: 딕셔너리의 키의 타입 지정

TValue: 딕셔너리의 값의 타입을 지정

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 정수 키와 문자열 값을 저장하는 Dictionary 생성
        Dictionary<int, string> dictionary = new Dictionary<int, string>();

        // 키-값 쌍 추가
        dictionary.Add(1, "One");
        dictionary.Add(2, "Two");
        dictionary.Add(3, "Three");

        // 키를 사용하여 값을 검색
        string value = dictionary[2];
        Console.WriteLine(value); // 출력: Two

        // 키-값 쌍 제거
        dictionary.Remove(1);

        // Dictionary의 모든 키-값 쌍을 반복 처리
        foreach (var pair in dictionary)
        {
            Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
        }

        // 키가 Dictionary에 존재하는지 확인
        if (dictionary.ContainsKey(3))
        {
            Console.WriteLine("Key 3 exists in the dictionary.");
        }
    }
}

 

① 하나의 배열이 주어지고, 해당 배열의 각 데이터는 숫자다.
배열 절반의 길이보다 큰 갯수만큼 특정 숫자가 들어가 있으면 해당 숫자,그렇지 않으면 -1을 리턴하는 함수를 만들어라. 

예: [2,7,7,7,1,7,2], 리턴값 : 7

using System;
using System.Collections.Generic;

class Program
{
    static int FindMajorityElement(int[] arr)
    {
        // 숫자와 빈도수를 저장하는 Dictionary 생성
        Dictionary<int, int> counts = new Dictionary<int, int>();
        
        // 각 숫자의 빈도수를 계산
        foreach (int number in arr)
        {
            if (counts.ContainsKey(number))
            {
                counts[number]++;
            }
            else
            {
                counts[number] = 1;
            }
        }
        
        // 배열의 길이의 절반을 계산
        int halfLength = arr.Length / 2;
        
        // 빈도수가 배열 길이의 절반보다 큰 숫자를 찾음
        foreach (var entry in counts)
        {
            if (entry.Value > halfLength)
            {
                return entry.Key;
            }
        }
        
        // 해당하는 숫자가 없는 경우 -1을 리턴
        return -1;
    }
    
    static void Main()
    {
        // 예제
        int[] arr = {2, 7, 7, 7, 1, 7, 2};
        int result = FindMajorityElement(arr);
        
        Console.WriteLine("리턴값: " + result); // 리턴값: 7
    }
}

 

 

② 최빈값 찾기: 주어진 배열에서 가장 많이 등장하는 숫자를 찾아서 반환하라. 만약 두 개 이상의 숫자가 같은 횟수로 등장한다면, 그 중 아무 숫자나 반환하라.

using System;
using System.Collections.Generic;

class Program
{
    static int FindMode(int[] arr)
    {
        if (arr == null || arr.Length == 0)
        {
            throw new ArgumentException("Input array should not be null or empty");
        }

        Dictionary<int, int> counts = new Dictionary<int, int>();

        // 배열의 모든 요소에 대해 반복하여 빈도수를 계산한다.
        foreach (int number in arr)
        {
            if (counts.ContainsKey(number))
            {
                counts[number]++;
            }
            else
            {
                counts[number] = 1;
            }
        }

        int maxCount = 0; // 최대 빈도수를 저장할 변수.
        int mode = 0; // 최빈값을 저장할 변수.

        // Dictionary의 모든 항목에 대해 반복한다.
        foreach (var entry in counts)
        {
            if (entry.Value > maxCount) // 현재 항목의 빈도수가 최대 빈도수보다 크면
            {
                maxCount = entry.Value; // 최대 빈도수를 현재 항목의 빈도수로 갱신한다.
                mode = entry.Key; // 최빈값을 현재 숫자로 설정한다.
            }
        }

        return mode; // 최빈값을 반환한다.
    }

    static void Main()
    {
        int[] arr = { 4, 1, 2, 2, 3, 3, 4 };

        try
        {
            int mode = FindMode(arr); // FindMode 메서드를 호출하여 최빈값을 얻는다.
            Console.WriteLine("Mode: " + mode); // 최빈값을 콘솔에 출력한다.
        }
        catch (ArgumentException e) // ArgumentException이 발생하면
        {
            Console.WriteLine(e.Message); // 예외 메시지를 콘솔에 출력한다.
        }
    }
}

 

 

+ Recent posts