[백준 1940] 주몽 - 투 포인터

🔗 문제

https://www.acmicpc.net/problem/1940

 

1940번: 주몽

첫째 줄에는 재료의 개수 N(1 ≤ N ≤ 15,000)이 주어진다. 그리고 두 번째 줄에는 갑옷을 만드는데 필요한 수 M(1 ≤ M ≤ 10,000,000) 주어진다. 그리고 마지막으로 셋째 줄에는 N개의 재료들이 가진 고

www.acmicpc.net

 

📝 풀이

처음에 배열을 정렬하고 투포인터 방식으로 풀면 쉽다

 

💻 코드 

package org.kyhslam.bakjun;

import java.util.Arrays;
import java.util.Scanner;

public class p1940 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int M = sc.nextInt();
        int[] arr = new int[N];

        for (int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }

        /*int N = 6;
        int M = 9;
        int[] arr = {2, 7, 4, 1, 5, 3};*/

        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
        Arrays.sort(arr);


        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
        int count = 0; // 개수

        for (int i = 0; i < arr.length; i++) {
            int x = arr[i];
            int right = i+1;

            while (right < arr.length) {
                int y = arr[right];
                int sum = x + y;

                if (sum == M) {
                    count++;
                }
                right++;
            }
        }

        System.out.println("count = " + count);
    }
}

'💾 알고리즘 > LeetCode_백준' 카테고리의 다른 글

[백준 1377] 버블 소트  (0) 2022.11.01
[백준 17298] 오큰수  (1) 2022.09.26
[백준 11660] 구간 합 구하기 5  (0) 2022.06.22
[LeetCode] 561. Array Partition I  (0) 2022.06.07
[LeetCode] 15. 세수의 합  (0) 2022.05.31

댓글

Designed by JB FACTORY