투 포인터 알고리즘을 사용한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/* baekjoon 2003 two pointer */
public class SumOfNumbers {
static int N;
static int M;
static int A[];
static int count;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
A = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
A[i] = Integer.parseInt(st.nextToken());
}
twoPointer(A);
System.out.println(count);
}
public static void twoPointer(int[] arr) {
int start = 0;
int end = 0;
int sum = 0;
while (true) {
if (sum >= M) {
sum -= arr[start++];
} else if (end == N) {
break;
} else {
sum += arr[end++];
}
if (sum == M) {
count++;
}
}
}
}
start, end, sum을 0으로 초기화
무한 루프 속에서 주어진 조건에 따라 인덱스와 sum을 조작
1. 합이 정해진 값(M)보다 큰 경우 -> 합에서 시작 인덱스의 요소를 제거하고 시작 인덱스 1 증가
2. 끝 인덱스가 배열의 끝에 도달했을 때 -> 종료
3. 합이 정해진 값(M)보다 작은 경우 -> 구하고 있는 합에 끝 인덱스 요소 추가 후 끝 인덱스 값 증가
4. 합과 M이 같다면 개수 증가
배경 지식이 제대로 잡혀있지 않는 상태에서 접근하면서 투 포인터에 대해 알아보면서 더 수월하게 이해할 수 있었다.