반응형
    
    
    
  3273번: 두 수의 합
n개의 서로 다른 양의 정수 a1, a2, ..., an으로 이루어진 수열이 있다. ai의 값은 1보다 크거나 같고, 1000000보다 작거나 같은 자연수이다. 자연수 x가 주어졌을 때, ai + aj = x (1 ≤ i < j ≤ n)을 만족하는
www.acmicpc.net
투 포인터를 이용하여 풀었습니다.
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 count = 0;
        int[] arr = Arrays.stream(br.readLine().split(" "))
                        .mapToInt(Integer::parseInt)
                        .sorted()
                        .toArray();
        int x = Integer.parseInt(br.readLine());
        int start = 0, end = n-1;
        while (start<end){
            int sum = arr[start] + arr[end];
            if (sum==x) count++;
            if (sum<=x) start++;
            else end--;
        }
        System.out.print(count);
    }
}

반응형
    
    
    
  'Algorithm' 카테고리의 다른 글
| 백준 11967번 불켜기 [ Java ] (0) | 2021.01.04 | 
|---|---|
| 백준 10757번 큰 수 A+B [ Java ] (0) | 2021.01.04 | 
| 백준 1431번 시리얼 번호 [ Java ] (0) | 2021.01.03 | 
| 백준 10825번 국영수 [ Java ] (0) | 2021.01.03 | 
| 백준 10813번 공 바꾸기 [ Java ] (0) | 2021.01.03 |