Today
-
Yesterday
-
Total
-
  • 프로그래머스 : 체육복
    코딩테스트 문제 풀이/프로그래머스 2023. 11. 22. 01:01

    다른사람 코드 _ 프로그래머스 다른사람풀이 첫번째

    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;
        }
    }

    로직이 무척 간단하다! 🤓

    학생의 수를 크기로 갖는 people 배열을 하나 생성 후 lost 배열에 있는 학생은 -1 reserve 배열에 있는 학생은 +1

    그리고 옷을 잃어버린 학생에게 옷을 빌려줄 수 있는지를 확인하기 위해 반복문을 돌려 people 배열을 탐색한다.

    1. 잃어버린 학생을 찾는다

    if (people[i] == -1) {  }

    2. 옷을 잃어버린 학생보다 하나 앞에 있는 학생에게 여벌옷이 있는지 확인한다.

     if(i-1>=0 && people[i-1] == 1) { }

    2-1. 있으면 잃어버린 학생은 옷을 갖게됨으로 +1 , 빌려주게된 학생은 옷을 하나 잃음 -1

     people[i]++;  people[i-1]--;

    2-2. 없으면 하나 뒤에 있는 학생을 탐색

     else if(i+1< people.length && people[i+1] == 1) {  }

    2-2-1. 있으면 잃어버린 학생은 옷을 갖게됨으로 +1 , 빌려주게된 학생은 옷을 하나 잃음 -1

     people[i]++;  people[i+1]--;

    2-3. 없으면 학생은 체육에 참여할수 없음

    else answer--;

    3. 반복문 종료 후 answer (참여 가능한 학생 수) 반환

    내코드 였던 것

    import java.util.Arrays;
    class Solution {
        public int solution(int n, int[] lost, int[] reserve) {
            int answer = n - lost.length;
            
            // 여벌옷이 있는 학생이 도난당한 경우 체크
            for (int i = 0; i < reserve.length; i++) {
                for (int j = 0; j < lost.length; j++) {
                    if (reserve[i] == lost[j]) {
                        reserve[i] = -1;
                        lost[j] = -1;
                        answer++;
                        break;
                    }
                }
            }
            
            // 옷 확인
            for (int i = 0; i < reserve.length; i++) {
                if (reserve[i] == -1) continue;
                
                for (int j = 0; j < lost.length; j++) {
                    if (lost[j] == -1) continue;
                    if (Math.abs(reserve[i] - lost[j]) == 1) {
                        lost[j] = -1;
                        answer++;
                        break;
                    }
                }
            }
            
            return answer;
        }
    }

    🤔

    처음 풀어본 날: 23.03.28 학습한 날 : 23.03.29 ~ 30

Designed by Tistory / Custom by 얼거스