본문 바로가기

프로그래머스 - JAVA

코딩테스트 연습 > 탐욕법(Greedy) > 구명보트

이전 코드

import java.util.*;

class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
        
        int i = 0;
        int j = people.length - 1;
        Arrays.sort(people);
        // 80, 70, 50, 50
        //     ans 1, i 1, j 3
        //     ans 2, i 2, j 3
        //     ans 3, i 3, j 2
        while (i <= j){
            if (i == j){
                answer ++;
                break;
            } else {
                if (people[i] + people[j] <= limit){
                    answer ++;
                    i ++;
                    j --;
                    if (i > j) {
                        break;  
                    } 
                } else {
                    answer ++;
                    j --;
                }
            }
        }
        
        return answer;
    }
}

최근 코드

import java.util.*;

class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
        Arrays.sort(people);
        int left = 0;
        int right = people.length - 1;
        
        while(left <= right){
            if (people[left] + people[right] <= limit){
                left ++;
                right --;
                answer ++;
            } else {
                right --;
                answer ++;
            }
        }
        return answer;
    }
}