728x90
조건
수열 안에서 두수를 합해서 X를 만족하는 쌍의 개수를 구하라!
Collections.sort(arrayList);
for (int i = 0; i < N / 2; i++) {
if (hs.contains(X - arrayList.get(i))) {
count++;
}
}
처음에 해쉬셋과 arrayList둘다 넣어서 값을 확인해줬는데,, 계속 틀렸다고 했다
정말 직접 더해야된다고 한다! 한개의 수로만 개수를 얻는것은 안된다고 함
package 두수의합;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
HashSet<Integer> hs = new HashSet<Integer>();
StringTokenizer st = new StringTokenizer(br.readLine()," ");
int[] arrayList = new int[N];
for(int i = 0; i < N; i++) {
int n = Integer.parseInt(st.nextToken());
hs.add(n);
arrayList[i] = n;
}
int X = Integer.parseInt(br.readLine());
int count = 0;
Arrays.sort(arrayList);
int startIdx = 0;
int endIdx = N-1;
while (startIdx < endIdx) {
int sum = arrayList[startIdx] + arrayList[endIdx];
if(sum == X) {
count++;
endIdx--;
startIdx++;
}
else if(sum > X) endIdx--; //합계가 x 보다 크면 종료인덱스 감소
else if(sum < X) startIdx++; //합계가 x 보다 작으면 시작인덱스 증가 }
}
System.out.println(count);
}
}
이진바이너리 트리 처럼 투포인터를 사용해서 점검해주는 것이였다
728x90
'CS > Algorithm' 카테고리의 다른 글
[ JAVA / 백준 : 1654 ] 랜선자르기 (0) | 2021.08.12 |
---|---|
[ JAVA / 백준 : 1920 ] 수 찾기 (0) | 2021.08.11 |
[ JAVA / 백준 : 1764 ] 듣보잡 (0) | 2021.08.09 |
[ JAVA / 백준 : 10815 ] 숫자 카드 (0) | 2021.08.09 |
[ JAVA / 백준 : 1427 ] 소트인사이드 (0) | 2021.08.08 |