기본 틀 :
using System;
public class Solution {
public int[] solution(int k, int[] score) {
int[] answer = new int[] {};
return answer;
}
}
풀이 1)
int 형 배열 매개변수 score를 Skip()함수와 Take() 함수를 이용해
일부 배열을 새로운 int형 배열(temp)에 담는다.
그 후, temp.Length 길이가 int 형 매개변수
k 보다 작을 경우
temp.Min()으로 가장 작은 값을
k 보다 클 경우
temp[k - 1]을
answer 배열에 담는다.
using System;
using System.Linq;
public class Solution
{
public int[] solution(int k, int[] score)
{
int[] answer = new int[score.Length];
for(int i = 0; i < score.Length; i++)
{
int[] temp = score.Skip(0).Take(i + 1).OrderByDescending(element => element).ToArray();
answer[i] = temp.Length < k ? temp.Min() : temp[k - 1];
}
return answer;
}
}
위의 코드는 반복문을 수행하면서 score 배열의 일부 배열을 계속 자르는 과정이 필요하다.
그래서, 수행시간이 기하급수적으로 높게 나오는 케이스가 존재하는 것으로 추측된다.
풀이 2)
socre 배열의 일부 배열을 계속 자르는 과정을 없애기 위해
List<int> 를 사용해 현재 가수의 점수를 Add()하는 방식으로 수정했다.
using System;
using System.Linq;
using System.Collections.Generic;
public class Solution
{
public int[] solution(int k, int[] score)
{
List<int> list = new List<int>();
int[] answer = new int[score.Length];
for(int i = 0; i < score.Length; i++)
{
list.Add(score[i]);
list.Sort();
list.Reverse();
answer[i] = list.Count < k ? list.Min() : list[k - 1];
}
return answer;
}
}
그럴 경우 위와 같이 풀이 1) 보다 풀이 2)의 수행시간이 더 짧은 것을 확인할 수 있었다.
'문제 풀기 > C#' 카테고리의 다른 글
55. 카드 뭉치 (0) | 2025.02.06 |
---|---|
54. 2016 (DateTime Class) (0) | 2025.02.06 |
52. 콜라 문제 (0) | 2025.02.05 |
51. 푸드 파이트 대회 (0) | 2025.02.05 |
50. 가장 가까운 글자 (0) | 2025.02.04 |