
내가 작성한 코드
import java.util.*;
class Solution {
public int solution(int[] topping) {
Map<Integer, Integer> rightMap = new HashMap<>(); // 오른쪽: 토핑별 개수 저장
Set<Integer> leftSet = new HashSet<>(); // 왼쪽: 토핑 종류 저장
int count = 0;
// 처음엔 전체가 오른쪽에 있음
for (int t : topping) {
rightMap.put(t, rightMap.getOrDefault(t, 0) + 1);
}
// 하나씩 왼쪽으로 옮기면서 비교
for (int i = 0; i < topping.length; i++) {
int top = topping[i];
// 왼쪽에 추가
leftSet.add(top);
// 오른쪽에서 제거
rightMap.put(top, rightMap.get(top) - 1);
if (rightMap.get(top) == 0) {
rightMap.remove(top);
}
// 두 쪽의 토핑 종류 수가 같으면 정답++
if (leftSet.size() == rightMap.size()) {
count++;
}
}
return count;
}
}
다른 사람의 코드
class Solution {
public int solution(int[] topping) {
int answer = 0;
int[] left = new int[10001], right = new int[10001]; // 토핑 번호 카운트용 배열들
int ls = 0, rs = 0; // 왼쪽과 오른쪽에서 각각 다른 토핑의 개수
for(var i : topping) right[i]++; // 오른쪽 배열에 모든 토핑을 넣음
for(var i : right) rs += i > 0 ? 1 : 0; // 오른쪽에서 다른 토핑의 개수 계산
for(var i : topping) {
right[i]--; // 현재 토핑을 왼쪽으로 옮기기 위해 오른쪽에서 제거
if (right[i] == 0) rs--; // 만약 오른쪽에서 해당 토핑이 더 이상 없다면 다른 토핑의 개수 감소
if (left[i] == 0) ls++; // 왼쪽에 해당 토핑이 처음 추가되면 다른 토핑의 개수 증가
left[i]++; // 왼쪽에 현재 토핑을 추가
if (rs == ls) answer++; // 왼쪽과 오른쪽에서 다른 토핑의 개수가 같다면 정답 카운트 증가
}
return answer;
}
}
Share article