알고리즘 공부/프로그래머스

(Java)프로그래머스 코딩테스트 연습 - 탐욕법(Greedy) - 구명보트

HRuler 2020. 10. 24. 01:46

1. 문제

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

 

코딩테스트 연습 - 구명보트

무인도에 갇힌 사람들을 구명보트를 이용하여 구출하려고 합니다. 구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고, 무게 제한도 있습니다. 예를 들어, 사람들의 몸무게가 [70kg, 50kg, 80kg, 5

programmers.co.kr

2. 나의 풀이

import java.util.Arrays;

class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
        Arrays.sort(people);
        int left = 0;
        int right = people.length - 1;
        while(right >= left) {
        	int weight = people[right--];
        	if(weight + people[left] <= limit) {
        		left++;
        	}
        	answer++;
        }
        /*
        //System.out.println(Arrays.toString(people));
        int people_su = people.length;
        System.out.println(people_su);
        boolean [] visited = new boolean [people_su];
        int k = limit;
        while(visited_check(visited)) {
        	for(int i = (people_su - 1); i >= 0; i = i - 1) {
        		if(visited[i] == false && k - people[i] >= 0) {
        			visited[i] = true;
        			k = k - people[i];
        		}
        	}
        	answer += 1;
        	k = limit;
        	System.out.println("visited : " + Arrays.toString(visited));
        	System.out.println("answer : " + answer);
        }
        */
        return answer;
    }
}

3. 다른 사람 풀이

import java.util.Arrays;

class Solution {
    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;
    }
}