Dictionary는 키와 값 쌍을 저장하는 컬렉션이다. 다른 언어에서는 '해시맵', '해시 테이블', '맵' 등으로 불리는 자료구조와 같다. Dictionary는 키를 사용하여 빠르게 데이터를 검색할 수 있도록 설계되어 있다.
Dictionary<TKey, TValue>는 두 개의 타입 매개변수를 사용한다
TKey: 딕셔너리의 키의 타입 지정
TValue: 딕셔너리의 값의 타입을 지정
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
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);
dictionary.Remove(1);
foreach (var pair in dictionary)
{
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}
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<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;
}
}
return -1;
}
static void Main()
{
int[] arr = {2, 7, 7, 7, 1, 7, 2};
int result = FindMajorityElement(arr);
Console.WriteLine("리턴값: " + result);
}
}
② 최빈값 찾기: 주어진 배열에서 가장 많이 등장하는 숫자를 찾아서 반환하라. 만약 두 개 이상의 숫자가 같은 횟수로 등장한다면, 그 중 아무 숫자나 반환하라.
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;
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);
Console.WriteLine("Mode: " + mode);
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
}
}