https://www.acmicpc.net/problem/3273
3273번: 두 수의 합
n개의 서로 다른 양의 정수 a1, a2, ..., an으로 이루어진 수열이 있다. ai의 값은 1보다 크거나 같고, 1000000보다 작거나 같은 자연수이다. 자연수 x가 주어졌을 때, ai + aj = x (1 ≤ i < j ≤ n)을 만족하는
www.acmicpc.net
저는 2중 for문, 이분탐색, 투포인트를 통해서 해결하였습니다.
2중 for문을 통해 두 수의 합이 목표 합과 같아지는 개수를 확인하였고, 이분탐색과 투포인트는 정렬후 진행하였습니다.
이분탐색은 목표 수에서 해당 수를 뺸 값이 존재하는지를 확인하여 문제를 풀었습니다. 이때 해당 수보다 뒤에 있는 것만 확인하였습니다. 투포인트는 맨앞과 맨 뒤에서 부터 시작하여 합이 목표값보다 크다면, 맨 뒤를 앞으로, 목표값보다 작다면 맨 앞을 뒤로 보내면서 목표값이 되는 개수를 구하여 문제를 풀었습니다.
package BOJ.twopoint;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class BOJ_3273 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] number = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++){
number[i] = Integer.parseInt(st.nextToken());
}
int targetSum = Integer.parseInt(br.readLine());
long result = calBinarySearch(number,targetSum,n);
System.out.println(result);
}
private static int calFor(int[] number , int targetSum , int n){
int result = 0;
for(int i = 0 ; i < n ; i++){
for(int j = i+1 ; j < n ; j++){
int sum = number[i] + number[j];
if(sum == targetSum){
result++;
}
}
}
return result;
}
private static int calBinarySearch(int[] number, int targetSum, int n){
Arrays.sort(number);
int result = 0;
for(int i = 0 ; i < n ; i++){
int targetNumber = targetSum - number[i];
int index = Arrays.binarySearch(number,i+1,number.length,targetNumber);
if(index >= 0){
result++;
}
}
return result;
}
private static int calTwoPoint(int[] number, int targetSum, int n){
Arrays.sort(number);
int startIndex = 0;
int endIndex = n-1;
int result= 0 ;
while(startIndex < endIndex){
int sum = number[startIndex] + number[endIndex];
if(sum == targetSum){
result++;
endIndex--;
continue;
}
if(sum < targetSum){
startIndex++;
continue;
}
if(sum > targetSum){
endIndex--;
continue;
}
}
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 2606번 바이러스 (JAVA) (1) | 2024.01.10 |
---|---|
백준 2805번 나무 자르기 (JAVA) (1) | 2024.01.09 |
백준 1197번 최소 스패닝 트리 (JAVA) (0) | 2024.01.07 |
백준 20922번 겹치는 건 싫어(JAVA) (1) | 2024.01.06 |
백준 2565번 전깃줄 (JAVA) (0) | 2024.01.05 |