TIL (Today I Learned)

99클럽 코테 스터디 19일차 TIL + 오늘의 학습 키워드

남 희 2024. 8. 9. 22:53

☑️ 문제: 구명보트

https://school.programmers.co.kr/learn/courses/30/lessons/42885

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

☑️ 설계

// 풀이 방법
// 1. 배열을 정렬시킨다.
// 2. (min, limit - min) 한쌍을 이루는 부분을 찾는다.
    // (1) limit - min 그 이상의 사람 수 answer에 더한다.
    // (2) (min, limit - min) 한쌍을 이뤘으므로, answer + 1한다.
// 2. 1번 과정을 min의 index가 limit - min의 index보다 커질 때까지 반복한다.

 

☑️ Code

import java.util.Arrays;

class Solution {
    public int solution(int[] people, int limit) {
        Arrays.sort(people);

        int answer = 0;
        int minIndex = 0;
        int maxIndex = people.length - 1;
        while (true) {
            int min = people[minIndex];
            for (int i = maxIndex; i >= minIndex; i--) {
                if (min <= limit - people[i]) {
                    answer += (maxIndex - i);
                    answer += 1;
                    maxIndex = i - 1;
                    break;
                }
                if (i == minIndex) {
                    answer += (maxIndex - minIndex + 1);
                    maxIndex = i;
                }
            }
            minIndex++;
            
            if (minIndex > maxIndex) { break; }
        }
        
        return answer;
    }
}

 

☑️ 기억하자

오늘 실수한 부분

  • 범위를 등호가 아니라 부등호를 써야하는데, if문에서 등호를 써버려서 테스트케이스만 맞고 실제로 제출했을 때 답이 거의 맞지 않는 현상이 생겼다. => "조건이 등호를 쓰는 게 맞는지, 부등호를 쓰는 게 맞는지 고민할 것."