class Solution {
public int solution(int n, int[] lost, int[] reserve) {
// 체육복을 하나 더 가져왔는데 누가 훔쳐간애 처리
for(int i=0; i< reserve.length; i++) {
for(int j=0; j< lost.length; j++)
if(reserve[i] == lost[j]) {
reserve[i] = 0;
}
}
int ok_give = 0; //체육복을 빌려줄수있는 학생 수
int duplicate = 0; // 중복 처리
// 잃어버린 학생의 수
int lost_length = lost.length;
// 여벌 체육복이 있는 학생의 수
int reserve_length = reserve.length;
for(int i=0; i<reserve.length; i++) {
duplicate=0;
int reserve_plus = reserve[i]+1;
int reserve_minus = reserve[i]-1;
for(int j=0; j<lost.length; j++){
int lost_index = lost[j];
if(lost_index == reserve_plus) {
ok_give++;
duplicate++;
}
if(lost_index == reserve_minus) {
ok_give++;
duplicate++;
}
if(duplicate == 2){
ok_give--;
}
}
}
int answer = 0;
int ok = 0;
if(lost.length < ok_give) {
ok = ok_give - lost.length;
answer = n-lost.length+ok_give-ok;
// 전체 학생수 - 잃어버린 학생의 수 + 여벌의 체육복을 가져와서 빌려줄수있는 학생의 수 + 중복 제거
}else{
answer = n-lost.length+ok_give;
// 전체 학생수 - 잃어버린 학생의 수 + 여벌의 체육복을 가져와서 빌려줄수있는 학생의 수
}
return answer;
}
}
코드실행은 성공했으나
체점을 하니 65점이나왔다.
도중에 테스트케이스를 뭘 놓친건지..
테스트케이스를 추가해서 다시 풀어봐야겠다..
다른 사람의 풀이법
import java.util.Arrays;
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = n - lost.length; Arrays.sort(lost); Arrays.sort(reserve); // 여벌 체육복을 가져온 학생이 도난당한 경우 for(int i=0; i<lost.length; i++) {
for(int j=0; j<reserve.length; j++) {
if(lost[i] == reserve[j]){ answer++; lost[i] = -1; reserve[j] = -1; break;
}
}
}
// 도난당한 학생에게 체육복 빌려주는 경우
for(int i=0; i<lost.length; i++) {
for(int j=0; j<reserve.length; j++) {
if((lost[i]-1 == reserve[j]) || (lost[i]+1 == reserve[j])){ answer++; reserve[j] = -1; break;
}
}
}
return answer;
}
}
'알고리즘' 카테고리의 다른 글
[프로그래머스] Java 문자열 내림차순 배치하기 (0) | 2022.05.31 |
---|---|
[프로그래머스] 두 개 뽑아서 더하기 (0) | 2022.02.11 |