[프로그래머스/Java/레벨 0/⭕️] n번째 원소까지

2023. 8. 6. 16:22·🐤 CodingTest

 

 

 

🗣️ 메모

배열과 리스트 등의 형태에 값을 넣는 방법은 다 다르다! 당연함

 

 

 


 

 

 

✏️ [n번째 원소까지]

문제 설명

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


제한사항
  • 2 ≤ num_list의 길이 ≤ 30
  • 1 ≤ num_list의 원소 ≤ 9
  • 1 ≤ n ≤ num_list의 길이 ___
입출력 예num_listnresult
[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

 

 

저작자표시 비영리 변경금지 (새창열림)
'🐤 CodingTest' 카테고리의 다른 글
  • [프로그래머스/Java/레벨 0/⭕️] 정수 부분
  • [프로그래머스/Java/레벨 0/⭕️] 수 조작하기
천재강쥐
천재강쥐
  • 천재강쥐
    디버거도 버거다
    천재강쥐
  • 전체
    오늘
    어제
    • Category (467)
      • 진짜 너무 궁금한데 이걸 나만 몰라...? (0)
      • 💾 Portfolio (2)
      • 🐤 CodingTest (28)
        • Java (20)
        • ᕕ(ꐦ°᷄д°᷅)ᕗ❌ (5)
      • 🚀 from error to study (142)
        • AI (1)
        • Cloud (2)
        • DB (12)
        • Front-End (16)
        • Github (14)
        • Java (39)
        • Mac (7)
        • Normal (29)
        • Server (22)
      • 📘 certificate (44)
        • 📘 리눅스마스터1급 (1)
        • 📘⭕️ 정보처리기사 (40)
        • 📘⭕️ SQLD (3)
      • 📗 self-study (234)
        • 📗 inflearn (35)
        • 📗 생활코딩 (8)
        • 📗 KH정보교육원 당산지원 (190)
      • 🎨 Scoop the others (0)
        • 📖 Peeking into other people.. (0)
        • 🇫🇷 (0)
        • 📘⭕️ 한국사능력검정시험 심화 (11)
        • 오블완 (4)
  • 인기 글

  • hELLO· Designed By정상우.v4.10.1
천재강쥐
[프로그래머스/Java/레벨 0/⭕️] n번째 원소까지
상단으로

티스토리툴바