티스토리 뷰

  • 문제 설명

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

 

  • 제한사항

    2 ≤ num_list의 길이 ≤ 30
    1 ≤ num_list의 원소 ≤ 9
    1 ≤ n ≤ num_list의 길이

 

  • 입출력 예

 

  • 입출력 예 설명

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

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

🤔 Arrays 클래스의 copyOfRange()

import java.util.Arrays;

class Solution {
    public int[] solution(int[] num_list, int n) {
        
        int[] answer = new int[num_list.length - n + 1];
        
        answer = Arrays.copyOfRange(num_list, n-1, num_list.length);
        
        return answer;
    }
}

 

🤔 for문

class Solution {
    public int[] solution(int[] num_list, int n) {
        
        int[] answer = new int[num_list.length - n + 1];
        
        for(int i = n-1, j = 0; i < num_list.length; i++, j++){
            answer[j] = num_list[i];
        }
        
        return answer;
    }
}
  • for문 안에서 변수를 두 개 사용했다.

for (초기화; 조건; 증감) {
    // 반복할 코드
}
  • 초기화와 증감 부분에서 쉼표(,)를 사용하면 여러 변수를 초기화하고, 동시에 증감시킬 수 있다.
for (int i = 0, j = 10; i < 5; i++, j--) {
    System.out.println("i: " + i + ", j: " + j);
}

/* 
i: 0, j: 10
i: 1, j: 9
i: 2, j: 8
i: 3, j: 7
i: 4, j: 6
*/

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함