Programming skills/알고리즘

프로그래머스 k번째수(정렬, 스택 큐로 )

제이커브(Jcurve) 2023. 10. 11. 23:05

K번째수

 

https://school.programmers.co.kr/learn/courses/30/lessons/42748

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


 

using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public int[] solution(int[] array, int[,] commands) {
        
        //2차원 배열의 행 갯수만큼 answer 배열 초기화
        int[] answer= new int[commands.GetLength(0)];
        //0부터 commands 2차원 배열의 행 갯수까지 반복
        for(int n = 0; n < commands.GetLength(0); n++){
            
            //각 i,j,k원소 매횟수마다 초기화
            int i = commands[n,0];
            int j = commands[n,1];
            int k = commands[n,2];
            //i번째부터 j까지 자른 배열선언
            int[] temp = new int[j - i +1];
            //자른 배열 크기만큼 반복하여 i번째부터 숫자대입
            for(int a = 0; a< temp.Length; a++){
                temp[a] = array[a+i-1];
                
            }
            //자른 배열 정렬
            Array.Sort(temp);
            answer[n]= temp[k-1];
            
        }
        
        //k번째 숫자 구하기
        return answer;
    }
}

List를 이용해서 풀어보기

using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public int[] solution(int[] array, int[,] commands) {
        List<int>answer = new List<int>();
        List<int>temp = new List<int>();
        
        for(int i =0; i<commands.GetLength(0); i++){
            //min 처음 위치(index라-1로 계산)
            int min = commands[i,0] - 1;
            //max(처음 자르는 위치에서 얼마나 계산하는지)
            int max = commands[i,1] - min;
            //min부터 max까지 요소 추출
            temp = array.ToList<int>().GetRange(min, max);
            temp.Sort();
            //특정위치 수 반환
            answer.Add(temp[commands[i,2] -1]);
        }
        return answer.ToArray();
        }
    }