[프로그래머스] 후보 키
2020. 4. 15. 16:13ㆍ프로그래머스/카카오
import java.util.*;
class Solution {
public int solution(String[][] relation) {
int answer = 0;
int rowsize = relation.length;
int colsize = relation[0].length;
List<Integer> candidates = new LinkedList<>();
for(int i=1; i< 1<<colsize; i++){
if(check(relation, rowsize, colsize , i) == true){
candidates.add(i);
}
}
Collections.sort(candidates, new Comparator<Integer>(){
public int countBit(int n){
int ret = 0;
while(n!=0){
if((n & 1)!=0){
ret ++;
}
n = n>>1;
}
return ret;
}
public int compare(Integer a, Integer b){
int x = countBit(a);
int y = countBit(b);
return x-y;
}
});
while(candidates.size() !=0){
int n = candidates.remove(0);
answer++;
for(Iterator<Integer> it = candidates.iterator(); it.hasNext();){
int x = it.next();
if((n&x)==n){
it.remove();
}
}
}
return answer;
}
private boolean check(String[][] relation, int rowsize, int colsize, int subset){
for (int a=0; a<rowsize-1; a++) {
for (int b=a+1; b<rowsize; b++){
boolean flag = true;
for(int c=0; c<colsize; c++){
if((subset & 1<<c) == 0){
continue;
}
if(!relation[a][c].equals(relation[b][c])){
flag = false;
break;
}
}
if(flag){
return false;
}
}
}
return true;
}
}
1. 여러가지 조합을 생각해야할 때 bit를 이용할 수 있다는 것을 이용하였다.
2. Iterator로 순회하지않고 일반적인 for문을 통해 순회하며 i를 계속 0부터 순회하도록 했더니 시간초과가 떴다.
3. Iterator에 대해 잘 공부하고 리스트의 원소가 삭제되거나 삽입될때는 이 방법을 사용해야겠다.
'프로그래머스 > 카카오' 카테고리의 다른 글
[프로그래머스] 불량 사용자 (0) | 2020.04.22 |
---|---|
[프로그래머스] 괄호변환 (0) | 2020.04.18 |
[프로그래머스] [Level 4]무지의 먹방 라이브 (0) | 2020.04.14 |
[프로그래머스][3차] 방금그곡 (0) | 2020.04.14 |
[프로그래머스][1차] 캐시 (0) | 2020.04.13 |