본문 바로가기
자료구조 & 알고리즘/문제풀이

구명보트 - 프로그래머스 (Java, level 2)

by 넬준 2022. 2. 18.

처음 풀이

 

import java.util.Arrays;
class Solution {
    public int solution(int[] people, int limit) {
        Arrays.sort(people);
        //짝의 수
        int count = 0;
        //최대한 무게 차이가 많이 나는 사람끼리 짝해야 최소값
        int index = people.length;
        //짝 지어진 (무거운)사람의 index
        //다음 cycle 때 index-1부터 탐색
        for(int n=0; n<index; n++) {
            for(int i=index-1; i>n; i--) {
                if((people[n]+people[i])<=limit) {
                    index = i;
                    count++;
                    break;
                }//if end
            }//for end
            //가장 가벼운 사람과 짝없는 경우 break;
            if(index==people.length) break;
        }//for end
        return people.length-count;
    }
}

 

 

다른 풀이

for문을 간략하게 만든 풀이

 

public int solution(int[] people, int limit) {
    Arrays.sort(people);
    int i = 0, j = people.length - 1;
    for (; i < j; --j) {
        if (people[i] + people[j] <= limit)
            ++i;
    }
    return people.length - i;
}

 

이중for문을 for문으로!

"--j" 

댓글