본문 바로가기
코딩테스트/프로그래머스 기초

[코딩테스트 Lv.0] n 번째 원소까지

by 블루데이제이 2025. 3. 8.
728x90
반응형
문제 설명

정수 리스트 num_list와 정수 n이 주어질 때, num_list의 첫 번째 원소부터 n 번째 원소까지의 모든 원소를 담은 리스트를 return하도록 solution 함수를 완성해주세요.

제한사항
2 ≤ num_list의 길이 ≤ 30
1 ≤ num_list의 원소 ≤ 9
1 ≤ n ≤ num_list의 길이 ___
입출력 예
num_list	n	result
[2, 1, 6]	1	[2]
[5, 2, 1, 7, 5]	3	[5, 2, 1]
입출력 설명
입출력 예 #1
[2, 1, 6]의 첫 번째 원소부터 첫 번째 원소까지의 모든 원소는 [2]입니다.

입출력 예 #2
[5, 2, 1, 7, 5]의 첫 번째 원소부터 세 번째 원소까지의 모든 원소는 [5, 2, 1]입니다.

내 풀이
Java
class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[n];
        
        for(int i = 0; i < n; i++){
            answer[i] = num_list[i];
        }
        return answer;
    }
}
C
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// num_list_len은 배열 num_list의 길이입니다.
int* solution(int num_list[], size_t num_list_len, int n) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    int* answer = (int*)malloc(sizeof(int) * n);
    int i;
    for(i = 0; i < n; i++){
        answer[i] = num_list[i];
    }    
    
    return answer;
}
Python
def solution(num_list, n):
    answer = num_list[:n]
    return answer

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


 

[코딩테스트 Lv.0] n개 간격의 원소들

문제 설명정수 리스트 num_list와 정수 n이 주어질 때, num_list의 첫 번째 원소부터 마지막 원소까지 n개 간격으로 저장되어있는 원소들을 차례로 담은 리스트를 return하도록 solution 

bluedayj.tistory.com

 

728x90
반응형