[2023 코딩테스트] 주몽

고지훈·2023년 6월 17일

[2023] CodingTest

목록 보기
5/12

2023.06.17 / 노력만이 살길.. 이번 문제를 푸는데 시간이 조금 걸렸다.

주몽

문제번호: 백준 온라인 저지 1940번
시간제한: 1초
난이도: 실버
문제링크: https://www.acmicpc.net/problem/1940

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int M = Integer.parseInt(br.readLine());

        String[] sArray = br.readLine().split(" ");
        int[] nArray = new int[sArray.length];
        for(int i = 0; i < sArray.length; i++) {
            nArray[i] = Integer.parseInt(sArray[i]);
        }

        Arrays.sort(nArray);

        int count = 0;
        int startIndex = 0;
        int endIndex = N-1;

        while(startIndex != endIndex) {
            if(nArray[startIndex] + nArray[endIndex] < M) {
                startIndex++;
            }else if(nArray[startIndex] + nArray[endIndex] > M) {
                endIndex--;
            }else if(nArray[startIndex] + nArray[endIndex] == M) {
                endIndex--;
                count++;
            }
        }
        System.out.println(count);
    }
}

저번 시간에 익혔던 투 포인터의 개념을 적용하여 문제를 해결할 수 있었다. 최초에는 합배열과 투 포인터의 개념을 섞어 적용하면 쉽게 풀 수 있지 않을까 했지만, 경우의 수가 예상했던 것과 달리 너무 적게 나와 문제를 실패했다.

그래서 30분간 생각한 방법은 다음과 같다.
1. 투 포인터의 개념은 적용하되, startIndex의 위치와 endIndex의 위치를 배열의 시작점과 끝지점으로 설정할 것
2. 배열은 무조건 정렬된 상태일 것 → 작은 수와 큰 수를 더한 값이 M이 되는지 체크하기 위해 배열을 정렬해야 함
3. 다음과 같은 순서로 조건문을 수행할 것

  • 배열[startIndex] + 배열[endIndex] < M일 경우 startIndex증가
  • 배열[startIndex] + 배열[endIndex] > M일 경우 endIndex감소
  • 배열[startIndex] + 배열[endIndex] == M일 경우 endIndex감소 및 count증가

위 3가지 방식을 생각하여 코드를 구성한 결과 통과할 수 있었다. 다양한 시각으로 볼 줄 알아야 하는데, 하나에 꽂히면 그것만 생각하게 되어 시간을 많이 지체하는 것 같다. 조금 더 넓은 범위의 시각으로 보는 연습을 해야할 것 같다.

profile
"계획에 따르기보다 변화에 대응하기를"

4개의 댓글

comment-user-thumbnail
2023년 8월 21일

Not only was your post informative, but it was also thought-provoking and provided valuable insights on the topic at hand. Your thorough research and https://slopeonline.org attention to detail were evident and added a great deal of credibility to your arguments.

답글 달기
comment-user-thumbnail
2024년 6월 7일

It helps me gain more useful knowledge. Thank you for sharing. https://cookieclicker-2.com/

답글 달기
comment-user-thumbnail
2024년 8월 15일

the thrilling beat controls your every move, from jumps to spins
https://geometry-dashfree.com/

답글 달기
comment-user-thumbnail
2025년 5월 8일

Your sharing is very detailed. I have read and applied it very effectively.
gunspin

답글 달기