체육복

J·2021년 4월 7일
0

코딩테스트 연습

목록 보기
24/28

import java.util.*;

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

        int yes = n - lost.length; //빌리지 않고 체육할 수 있는 학생수
        int lend = 0; //빌려준 학생수

        int cnt=0;
        int length = lost.length;
        if(lost.length>reserve.length) length = reserve.length;
        
	//내가 내꺼 입을 때
        for(int i=0;i<length;i++){
            for(int j=0;j<length;j++){
                if( reserve[i] == lost[j] ) {
                    reserve[i] = -1;
                    lost[j] =-99;
                    cnt++;
                    break;
                 }
            }
        }
        
	//앞뒤의 숫자 비교를 위해 정렬
        Arrays.sort(lost);
        Arrays.sort(reserve);

        for(int i =0;i<reserve.length;i++){
            for(int j=lend;j<lost.length;j++){
               if( reserve[i]-1 == lost[j] || reserve[i]+1 == lost[j]) {
                    lend++;                   
                    //System.out.println("reserve"+ reserve[i]);
                    //System.out.println("lost"+ lost[j]);
                    break;
                }
            }
        }

        answer = yes + lend+ cnt;
        return answer;
    }
}

내꺼 내가 입을 때인 경우


        int [] lost1 = {1,2,3};
        int [] reserve1 = {2,3,4};
        System.out.println(solution(5,lost1,reserve1));//4

        int [] lost2 = {2,3,4};
        int [] reserve2 = {1,2,3};
        System.out.println(solution(5,lost2,reserve2));//4

다른 사람 코드

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int[] people = new int[n];
        int answer = n;

        for (int l : lost) 
            people[l-1]--;
        for (int r : reserve) 
            people[r-1]++;

        for (int i = 0; i < people.length; i++) {
            if(people[i] == -1) {
                if(i-1>=0 && people[i-1] == 1) {
                    people[i]++;
                    people[i-1]--;
                }else if(i+1< people.length && people[i+1] == 1) {
                    people[i]++;
                    people[i+1]--;
                }else 
                    answer--;
            }
        }
        return answer;
    }
}

0개의 댓글