[프로그래머스] 리스트 자르기

당당·2023년 4월 28일
0

프로그래머스

목록 보기
61/245

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

📔문제

정수 n과 정수 3개가 담긴 리스트 slicer 그리고 정수 여러 개가 담긴 리스트 num_list가 주어집니다. slicer에 담긴 정수를 차례대로 a, b, c라고 할 때, n에 따라 다음과 같이 num_list를 슬라이싱 하려고 합니다.

  • n = 1 : num_list의 0번 인덱스부터 b번 인덱스까지
  • n = 2 : num_lista번 인덱스부터 마지막 인덱스까지
  • n = 3 : num_lista번 인덱스부터 b번 인덱스까지
  • n = 4 : num_lista번 인덱스부터 b번 인덱스까지 c 간격으로

올바르게 슬라이싱한 리스트를 return하도록 solution 함수를 완성해주세요.


🚫제한사항

n 은 1, 2, 3, 4 중 하나입니다.
slicer의 길이 = 3
slicer에 담긴 정수를 차례대로 a, b, c라고 할 때
0 ≤ a ≤ b ≤ num_list의 길이 - 1
1 ≤ c ≤ 3
5 ≤ num_list의 길이 ≤ 30
0 ≤ num_list의 원소 ≤ 100


📝입출력 예

nslicernum_listresult
3[1, 5, 2][1, 2, 3, 4, 5, 6, 7, 8, 9][2, 3, 4, 5, 6]
4[1, 5, 2][1, 2, 3, 4, 5, 6, 7, 8, 9][2, 4, 6]

📝입출력 예 설명

입출력 예 #1

[1, 2, 3, 4, 5, 6, 7, 8, 9]에서 1번 인덱스부터 5번 인덱스까지 자른 리스트는 [2, 3, 4, 5, 6]입니다.


입출력 예 #2

[1, 2, 3, 4, 5, 6, 7, 8, 9]에서 1번 인덱스부터 5번 인덱스까지 2개 간격으로 자른 리스트는 [2, 4, 6]입니다.


🧮알고리즘 분류

  • 리스트(배열)

📃소스 코드

class Solution {
    public int[] solution(int n, int[] slicer, int[] num_list) {
        int[] answer;
        int a=slicer[0];
        int b=slicer[1];
        int c=slicer[2];
        int len=num_list.length;
        
        
        if(n==1){
            answer=new int[b+1];
            for(int i=0;i<=b;i++){
                answer[i]=num_list[i];
            }
        }
        else if(n==2){
            answer=new int[len-a];
            int count=0;
            for(int i=a;i<len;i++){
                answer[count]=num_list[i];
                count++;
            }
        }
        else if(n==3){
            answer=new int[b-a+1];
            int count=0;
            for(int i=a;i<=b;i++){
                answer[count]=num_list[i];
                count++;
            }
        }
        else{
            
            
            if((a+b)/c ==0){
                answer= new int[1];
            }
            else{
                int size=(b-a+1)/c + (b-a+1)%c;
                if(a==0){
                    answer=new int[size];
                }
                else{
                    answer=new int[size];
                }
                
            }
            
            int count=0;
            for(int i=a;i<=b;i=i+c){
                answer[count]=num_list[i];
                count++;
            }
        }
        return answer;
    }
}

📰출력 결과


📂고찰

반례를 겨우 찾았다.
n= 4, slicer=[0,4,2], num_list=[4,3,5,2,5]

그냥 예외가 발생했다. 그래서 크기를 어떻게 줘야 할까 하다가 b-a+1로 줬더니 해결됐다.

profile
MySQL DBA 신입 지원

0개의 댓글