본문 바로가기

프로그래머스

프로그래머스 - 체육복

내 코드 - 오답


탐욕 알고리즘이라는 게 있다고 하는데,

문제의 성격이 일치해야 적용할 수 있는데다가, 좀 직관적인 거라 알고리즘이라는 느낌이 잘 안든다.

뭔 말인지 잘 모르겠다.


아래 코드 오답 이유는,

한 학생이 여분을 가지고 있고 + 도둑도 맞을 수 있다는 점을 빼먹어서이다.


테스트코드에 하나 추가해 주었으면 더 좋을 거 같다.

class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = n - lost.length;

/**
* 탐욕 알고리즘
*/
outer:
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if (lost[i] - reserve[j] == 1 || lost[i] - reserve[j] == -1) {
reserve[j] += 100;
answer++;
continue outer;
}
}
}
return answer;
}
}


고친 코드

class Solution {
public int solution(int n, int[] lost, int[] reserve) {
/**
* 평범한 학생 수
* (Not lost, Not reserve)
*/
int answer = n - lost.length;

/**
* 여벌 + 도둑맞은 학생 = 평범한 학생 -> -1로 처리
*/
outer1:
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if (lost[i] == reserve[j]) {
lost[i] = -1;
reserve[j] = -1;

/**
* 평범한 학생수 ++
*/
answer++;
continue outer1;
}
}
}

/**
* 탐욕 알고리즘
*/
outer2:
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if ((lost[i] != -1 && reserve[j] != -1) && (lost[i] - reserve[j] == 1 || lost[i] - reserve[j] == -1)) {
reserve[j] += 100;
answer++;
continue outer2;
}
}
}
return answer;
}
}



다른 사람 코드는 더 길고, 딱히 참고할 게 없었음

'프로그래머스' 카테고리의 다른 글

프로그래머스 - 124 나라의 숫자  (0) 2019.01.13
프로그래머스 - 탑  (0) 2019.01.12
프로그래머스 - 예산  (0) 2019.01.10
프로그래머스 - 2016년  (0) 2019.01.10
프로그래머스 - 핸드폰 번호 가리기  (0) 2019.01.10