C# 알고리즘 코드카타

48. K번째수

잼잼재미 2023. 12. 4. 09:49

 

public static int[] solution(int[] array, int[,] commands)
{
    int[] answer = new int[commands.GetLength(0)];
    List<int> nums = new List<int>();

    for (int j = 0; j < commands.GetLength(0); j++)
    {
        for (int i = commands[j, 0] - 1; i <= commands[j, 1] - 1; i++)
        {            
            nums.Add(array[i]);
        }

        nums.Sort();

        answer[j] = nums[commands[j, 2] - 1];

        for (int i = 0; i < commands[j,1] - commands[j,0] + 1; i++)
        {
            nums.RemoveAt(0);
        }
    }
    return answer;
}

List의 모든 내용을 삭제하기 위해 RemoveAt을 for문으로 반복했다. 더 간단하게 Clear() 함수를 사용하면 된다.

 

 

다른 풀이


public static int[] solution(int[] array, int[,] commands)
{
    int[] answer = new int[commands.GetLength(0)];
    List<int> nums = new List<int>();

    for (int j = 0; j < commands.GetLength(0); j++)
    {
        for (int i = commands[j, 0] - 1; i <= commands[j, 1] - 1; i++)
        {            
            nums.Add(array[i]);
        }

        nums.Sort();
        answer[j] = nums[commands[j, 2] - 1];
        nums.Clear();
    }
    return answer;
}

'C# 알고리즘 코드카타' 카테고리의 다른 글

50. 가장 가까운 같은 글자  (1) 2023.12.06
49. 두 개 뽑아서 더하기  (0) 2023.12.05
47. 문자열 내 마음대로 정렬하기  (1) 2023.11.29
46. 숫자 문자열과 영단어  (1) 2023.11.28
45. 시저 암호  (0) 2023.11.27