[PROG] 42862 체육복

호호빵·2022년 9월 14일
0

Algorithm

목록 보기
25/46

문제

나의 풀이

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

        for (int i = 0; i < lost.length; i++) {
            for (int j = 0; j < reserve.length; j++) {
                if (lost[i] != 0 && reserve[j] != 0 && lost[i] == reserve[j]) {
                    lost[i] = 0;
                    reserve[j] = 0;
                    cnt++;
                }
            }
        }


        for (int i = 0; i < lost.length; i++) {
            for (int j = 0; j < reserve.length; j++) {
                if (lost[i] != 0 && reserve[j] != 0 && (lost[i] - 1 == reserve[j]) || (lost[i] + 1 == reserve[j])) {
                    lost[i] = 0;
                    reserve[j] = 0;
                    cnt++;
                }
            }
        }

        answer = n - lost.length + cnt;
        return answer;
    }
  • 통과하지 못하는 테스트케이스가 있었는데 정렬을 통해 해결해야한 다는 것을 알았다.

sort 정렬 풀이

import java.util.Arrays;

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

        Arrays.sort(lost);     		// 정렬 
        Arrays.sort(reserve);

        for (int i = 0; i < lost.length; i++) {		// lost 인 학생이 reserve 학생이라면
            for (int j = 0; j < reserve.length; j++) {
                if (lost[i] == reserve[j]) {
                    lost[i] = 0;
                    reserve[j] = 0;
                    cnt++;
                }
            }
        }


        for (int i = 0; i < lost.length; i++) {
            for (int j = 0; j < reserve.length; j++) {
                if (lost[i] != 0 && reserve[j] != 0 && (lost[i] - 1 == reserve[j]) || (lost[i] + 1 == reserve[j])) {
                    lost[i] = 0;
                    reserve[j] = 0;
                    cnt++;
                }
            }
        }

        answer = n - lost.length + cnt;
        return answer;
    }
  • 처음에 Arrays.stream(lost).sorted(); 로 정렬을 시도했고 틀렸다.

sort 방법

    Arrays.stream(lost).sorted();
    Arrays.stream(reserve).sorted();
    System.out.println(Arrays.toString(lost));
profile
하루에 한 개념씩

0개의 댓글