https://www.acmicpc.net/problem/3273
문제
풀이
package baekjoon.solution;
import java.util.Scanner;
public class Baekjoon_3273 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
int[] arr = new int[T];
int a = 0;
int cnt = 0;
for (int i = 0; i < T; i++) {
arr[i] = scan.nextInt();
}
int sum = scan.nextInt();
///----입력값 끝---
for (int i = 0; i < T - 1; i++) {
for (int j = 1 + a; j < T; j++) {
if (arr[i] + arr[j] == sum) {
cnt++;
a++;
}
}
}
System.out.println(cnt);
}
}
2중 for문을 이용해서 문제를 풀면, 시간이 초과한다고 한다.
다른 풀이 방법을 알아보자.
소스코드
package baekjoon.solution;
import java.util.Arrays;
import java.util.Scanner;
public class Baekjoon_3273 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
int arr[] = new int[T];
for(int i=0;i<arr.length;i++)
arr[i] = scan.nextInt();
Arrays.sort(arr);
//Arrays 클래스의 sort메소드..(정렬을 해준다)
int result = scan.nextInt();
int sum = 0;
int count = 0;
int end = T-1;
int start = 0;
while(start<end) {
if (arr[start] + arr[end] == result) {
count++;
start++;
end--;
} else if (arr[start] + arr[end] < result)
start++;
else
end--;
}
System.out.println(result);
}
}