문제 풀기/C#

48. K번째 수 정렬(Skip, Take 메서드)

kagan-draca 2025. 2. 4. 14:35

 

기본 틀 :

 

using System;

public class Solution {
    public int[] solution(int[] array, int[,] commands) {
        int[] answer = new int[] {};
        return answer;
    }
}

 

문제를 보고 매개변수로 주어진 array의 요소의 일부를 잘라 올 필요성을 느꼈다.

 

그래서, 인터넷을 통해 배열의 일부를 복사하는 방법을 찾아 본 결과 많은 함수가 존재했다.

 

1. Array.Copy(원본 배열, 시작 index, 결과를 담을 배열, 결과를 담을 배열의 시작 위치, 자를 개수)

 

위와 같이 Array.Copy()는 사용 방법이 복잡하고 매개변수의 인자가 너무 많은 관계로 사용하지 않았다.

 

2. Linq의 Skip(시작 index), Take(개수) 메서드

 

int[] intArray = { 0, 10, 20, 30, 40, 50, 60 };
int[] newArray = intArray.Skip(2).ToArray();
// 결과 : {20, 30, 40, 50, 60}

 

위와 같이 Skip()함수는 기존 배열에서 시작 Index를 지정해 배열을 자를 수 있다.

 

Take() 함수는

 

int[] intArray = { 0, 10, 20, 30, 40, 50, 60 };
int[] newArray = intArray.Skip(2).Take(3).ToArray();
// 결과 : { 20, 30, 40 }

으로 input 값 만큼 시작 Index에서 가져오는 메서드 입니다.

 

위의 두 함수를 활용해서 

 

using System;
using System.Linq;

public class Solution {
    public int[] solution(int[] array, int[,] commands) 
    {
        int[] result = new int[commands.GetLength(0)];
        
        for(int i = 0; i < result.Length; i++)
        {
            int startIndex = commands[i,0] - 1;
            int count = commands[i,1] - startIndex;
            int findIndex = commands[i,2] - 1;
            int temp = array.Skip(startIndex).Take(count).OrderBy(element => element).ToArray()[findIndex];
            result[i] = temp;
        }
        
        return result;
    }
}

 

위와 같이 commands의 1차원 배열 내부 요소 만큼

 

반복문을 수행하면서 일부 복사한 배열을 정렬하고

 

찾고자 하는 index의 요소를 result 배열에 저장할 수 있었다.