🗣️ 메모
배열과 리스트 등의 형태에 값을 넣는 방법은 다 다르다! 당연함
✏️ [n번째 원소까지]
문제 설명
정수 리스트 num_list와 정수 n이 주어질 때, num_list의 첫 번째 원소부터 n 번째 원소까지의 모든 원소를 담은 리스트를 return하도록 solution 함수를 완성해주세요.
제한사항
- 2 ≤ num_list의 길이 ≤ 30
- 1 ≤ num_list의 원소 ≤ 9
- 1 ≤ n ≤ num_list의 길이 ___
[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]입니다.
🔥 TRY #1
👉🏻 배열.put은 자바스크립트의 배열에 값을 추가하는 방법임
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = {};
for(int i = 0; i < n; i++) {
anwser.put(num_list[i]);
}
return answer;
}
}
👉🏻 .add는 list일 때 가능한 문법임
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = {};
for(int i = 0; i < n; i++) {
answer.add(num_list[i]);
}
return answer;
}
}
👉🏻 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Solution.solution(Unknown Source)
👉🏻 길이가 0인 배열에 1, 2, 3번째 등의 인덱스에 값을 넣으려고 해서 발생한 오류
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = {};
for(int i = 0; i < n; i++) {
answer[i] = num_list[i];
}
return answer;
}
}
👉🏻 /Solution.java:3: error: array dimension missing
int[] answer = new int[];
👉🏻 자바에서는 배열은 필시! 길이를 지정해 줘야 함
(자바스크립트에서는 배열 길이 지정이 필수가 아니고, 자바에서는 ArrayList는 길이를 미리 지정해 주지 않아도 됨)
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;
}
}
👉🏻 n 만큼의 배열 길이를 다시 선언해 준 뒤 코드 실행
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;
}
}
🎉🎊💫✨⚡️⭐️🌟 [실행 결과]
출처: 프로그래머스 코딩 테스트 연습,https://school.programmers.co.kr/learn/challenges
코딩테스트 연습 | 프로그래머스 스쿨
개발자 취업의 필수 관문 코딩테스트를 철저하게 연습하고 대비할 수 있는 문제를 총망라! 프로그래머스에서 선발한 문제로 유형을 파악하고 실력을 업그레이드해 보세요!
school.programmers.co.kr