공부/C#

[C#] 코딩테스트 참고용

굴러다니다니 2025. 3. 7. 23:59

유니티만 하다가 와서 코딩테스트때 유용할 함수 / 변수를 잘 사용하지 못할까봐 나를 위해 모아둔다

 

using System.Collections.Generic; -> List, Queue, Dictionary 등 사용

 

1. Dictionary<TKey, TValue>

  • 키-값(key-value) 쌍을 저장하는 자료구조
  • key를 기준으로 value를 빠르게 찾을 수 있음
  • 중복된 키를 허용하지 않으며, key를 사용해 데이터를 조회하거나 수정 가능
  • 내부적으로 해시 테이블을 사용하여 평균적으로 O(1)의 접근 속도를 가짐
  • value가 중요할 때 사용
  • Contains가 아닌 ContainsKey사용
  • 접근시 dic[key] 로 접근
var a = new Dictionary<string,string>();

var myTable = new Dictionary<string, string>();
      myTable.Add("Hokkaido", "Sapporo");
      myTable.Add("Iwate", "Morioka");
      myTable.Add("Miyagi", "Sendai");
       foreach(KeyValuePair<string, string> item in myTable) {
        Console.WriteLine("[{0}:{1}]", item.Key, item.Value);  
      }
      foreach(string Key in myTable.Keys) {
        Console.WriteLine(Key);  
      }
      foreach(string Value in myTable.Values) {
        Console.WriteLine(Value);  
      }
      Console.WriteLine("[{0}:{1}]", str, myTable[str]);  
      
      Console.ReadKey();
      
      if(myTable.ContainsKey(str)) {
        Console.WriteLine("{0}은(는) 이미 Key로 사용되고 있습니다.", str);

 

2. HashSet<T>

  • 유일한 값(중복 없는 데이터)을 저장하는 자료구조
  • Key-Value 형태가 아니라, 값(value)만 저장
  • 중복된 값은 자동으로 제거
  • 내부적으로 해시 테이블을 사용하여 평균적으로 O(1)의 접근 속도를 가짐

 

3. Array

bool[] visited = new bool[크기];

array.Length;

array.GetLength(0);

Array.Sort(array);

Array.Reverse(array);

 

4. List

List<int> list = new List<int>();

- list.Contains(a) -> true / false

- list.Add(a)

✅ Sort((a, b) => 비교식) 의 동작 원리

  • 비교식이 음수 → a가 b보다 앞에 위치
  • 비교식이 양수 → b가 a보다 앞에 위치
  • 비교식이 0 → 순서를 유지
List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };

// 오름차순 정렬 (작은 숫자가 먼저 오도록)
numbers.Sort((a, b) => a - b);
Console.WriteLine(string.Join(", ", numbers)); // 출력: 1, 2, 3, 5, 8

// 내림차순 정렬 (큰 숫자가 먼저 오도록)
numbers.Sort((a, b) => b - a);
Console.WriteLine(string.Join(", ", numbers)); // 출력: 8, 5, 3, 2, 1

b.CompareTo(a)는

  • b가 크면 1 → b가 앞
  • a가 크면 -1 → a가 앞
//응용 코드
songList.Sort((a, b) => 
    b.Item2 == a.Item2 ? a.Item1.CompareTo(b.Item1) : b.Item2.CompareTo(a.Item2)
);

 

📌 정리

오름차순 정렬 list.Sort((a, b) => a - b); 작은 값이 앞에 위치
내림차순 정렬 list.Sort((a, b) => b - a); 큰 값이 앞에 위치
문자열 정렬 list.Sort((a, b) => a.CompareTo(b)); 사전 순 정렬
복합 조건 list.Sort((a, b) => 조건1 ? 조건2 : 조건3); 다중 조건 정렬

 

Queue

Queue<(int, int)> queue = new Queue<(int, int)>();

- queue.Enqueue((0, 0)); 

- queue.Dequeue();

 

Stack

Stack<int> stack = new Stack<int>();

int a = stack.Pop();

stack.Push(a);

stack.Peek(); -> 맨 위의 값 확인

 

int.Parse(new string('5', i)) 5를 i번 반복한 string을 int로 바꿈

728x90
반응형