728x90
https://school.programmers.co.kr/learn/courses/30/lessons/132265
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
1. Java
import java.util.*;
class Solution {
public int solution(int[] topping) {
int answer = 0;
int n = topping.length;
Map<Integer,Integer> map1 = new HashMap<>();
Map<Integer,Integer> map2 = new HashMap<>();
for ( int i = 0; i < 1; ++i ) {
int t = topping[i];
map1.put( t, map1.getOrDefault(t, 0) + 1 );
}
for ( int i = 1; i < n; ++i ) {
int t = topping[i];
map2.put( t, map2.getOrDefault(t, 0) + 1 );
}
for ( int i = 1; i < n; ++i ) {
if ( map1.size() == map2.size() ) {
answer++;
}
int t = topping[i];
map1.put( t, map1.getOrDefault(t, 0) + 1 );
map2.put( t, map2.getOrDefault(t, 0) - 1 );
if ( map2.get(t) <= 0 ) {
map2.remove(t);
}
}
return answer;
}
}
더보기
import java.util.*;
class Solution {
public int solution(int[] topping) {
int answer = 0;
int n = topping.length;
for ( int i = 1; i < n - 1; ++i ) {
Set<Integer> set1 = new HashSet<>();
for ( int j = 0; j < i; ++j ) {
set1.add(topping[j]);
}
Set<Integer> set2 = new HashSet<>();
for ( int j = i; j < n; ++j ) {
set2.add(topping[j]);
}
if ( set1.size() == set2.size() ) {
answer++;
}
}
return answer;
}
}
2. Python
def solution(topping):
answer = 0
n = len(topping)
dic1 = {}
dic2 = {}
dic1[topping[0]] = 1
for i in range(1, n) :
t = topping[i]
dic2[t] = dic2.get(t, 0) + 1
for i in range(1, n) :
if len(dic1) == len(dic2) :
answer += 1
t = topping[i]
dic1[t] = dic1.get(t, 0) + 1
dic2[t] = dic2.get(t, 0) - 1
if dic2[t] <= 0 :
dic2.pop(t)
return answer
반응형
'코딩 문제 풀기 ( Algorithm problem solving ) > 프로그래머스 ( Programmers )' 카테고리의 다른 글
[프로그래머스(Programmers)][Java,Python] (Lv2) 택배상자 (0) | 2025.04.08 |
---|---|
[프로그래머스(Programmers)][Java,Python] (Lv2) 뒤에 있는 큰 수 찾기 (0) | 2025.04.03 |
[프로그래머스(Programmers)][Java,Python] (Lv2) 할인 행사 (0) | 2025.04.02 |
[프로그래머스(Programmers)][Java,Python] (Lv2) 연속 부분 수열 합의 개수 (0) | 2025.04.02 |
[프로그래머스(Programmers)][Java,Python] (Lv2) 귤 고르기 (0) | 2025.04.02 |