백준_알고리즘 수업 - 삽입 정렬 1

LeeYulhee·2023년 8월 31일
0

💻 문제 출처 : 백준_알고리즘 수업 - 삽입 정렬 1

👉 내가 작성한 답


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] firstLine = br.readLine().split(" ");
        String[] secondLine = br.readLine().split(" ");

        int[] intArray = new int[Integer.parseInt(firstLine[0])];
        int target = Integer.parseInt(firstLine[1]);
        int count = 0;

        for(int i = 0; i < secondLine.length; i++) {
            intArray[i] = Integer.parseInt(secondLine[i]);
        }

        for(int i = 1; i < intArray.length; i++) {
            int beforeIndex = i - 1;
            int newItem = intArray[i];

            while(0 <= beforeIndex && newItem < intArray[beforeIndex]) {
                intArray[beforeIndex + 1] = intArray[beforeIndex];
                beforeIndex--;
                count++;
                if(count == target) System.out.println(intArray[beforeIndex + 1]);
            }
            if(beforeIndex + 1 != i) {
                intArray[beforeIndex + 1] = newItem;
                count++;
                if(count == target) System.out.println(intArray[beforeIndex + 1]);
            }
        }

        if(count < target) System.out.println(-1);
    }
}

📌 문제 풀이 설명

  • BufferedReader를 생성
  • String 배열 firstLine을 생성해서 입력된 값을 “ “로 나눠 저장
  • String 배열 secondLine을 생성해서 입력된 값을 “ “로 나눠 저장
  • int 배열을 firstLine의 첫 번째 값 크기로 생성(int로 변환)
  • int 변수 target에 firstLine의 두 번째 값을 대입하고(int로 변환) int 변수 count를 생성 후 0으로 초기화
  • for문으로 0부터 secondLine의 길이 미만까지 순회
    • intArray[i]에 secondLint[i]를 int로 변환해서 넣음
  • for문으로 1부터 intArray의 길이 미만까지 1씩 증가하며 순회
    • int 변수 beforeIndex에 i - 1을 대입하고 int 변수 newItem에 intArray[i]를 대입
    • while문으로 beforeIndex가 0보다 크거나 같고, newItem이 intArray[beforeIndex] 미만인 경우(현재 값이 앞의 값보다 작은 경우)
      • intArray[beforeIndex + 1]에 intArray[beforeIndex]를 대입
        • 앞의 값을 현재 값의 인덱스 위치에 넣음
      • beforeIndex를 1 줄이고, count를 1 증가
      • 만약 count가 target과 같다면, 방금 이동한 값인 intArray[beforeIndex + 1]을 출력
    • 만약 beforeIndex + 1 ≠ i면(beforeIndex가 앞의 과정을 통해 들어가야 하는 위치보다 - 1 되어 있음)
      • intArray[beforeIndex + 1]에 newItem을 대입하고 count 1 증가
      • 만약 count가 target과 같다면, 방금 이동한 값인 intArray[beforeIndex + 1]을 출력
  • for문 종료 후 만약 count가 target 미만이면 -1 출력
profile
공부 중인 신입 백엔드 개발자입니다

0개의 댓글