코딩테스트/분할정복|이진탐색|투포인터
[투포인터] 백준 3273 두 수의 합 Java
유(YOO)
2020. 12. 27. 14:45
https://www.acmicpc.net/problem/3273
2. 오름차순 정렬 후 두 포인터
정렬 후, low와 high라는 변수를 생성하여 배열의 앞과 뒤에서부터 탐색
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n, x, ans=0, low, high;
n=sc.nextInt();
low=0;
high=n-1;
int a[] = new int[n];
for(int i=0; i<n; i++)
{
a[i]=sc.nextInt();
}
x=sc.nextInt();
Arrays.sort(a);
while(low<high) // mid로 이진탐색도 가능
{
if(a[low]+a[high]==x)
{
ans++;
low++;
high--;
}
else if(a[low]+a[high]<x)
{
low++;
}
else {
high--;
}
}
System.out.println(ans);
}
}
1. 배열
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n, x, ans=0;
n=sc.nextInt();
int a[] = new int[n];
for(int i=0; i<n; i++)
{
a[i]=sc.nextInt();
}
x=sc.nextInt();
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(a[i]+a[j]==x)
{
ans++;
}
}
}
System.out.println(ans);
}
}
시간 초과