[프로그래머스]Level.2 탐욕법(greedy) 구명보트
2021. 1. 14. 20:10ㆍAlgorithm/프로그래머스
코딩테스트 연습 - 구명보트
무인도에 갇힌 사람들을 구명보트를 이용하여 구출하려고 합니다. 구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고, 무게 제한도 있습니다. 예를 들어, 사람들의 몸무게가 [70kg, 50kg, 80kg, 5
programmers.co.kr
첫번쨰 풀이-효율성 실패(1번 3번)
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit) {
int answer = 0;
int num=1;
sort(people.begin(),people.end());
while(1){
int weight=limit-people.back();
people.pop_back();
if(weight!=0&&people.front()<=weight){
for(int i=0;i<people.size();i++){
if(people[i]>weight) continue;
people.erase(people.begin()+i);
break;
}
}
if(people.size()==0) break;
else num++;
}
answer=num;
return answer;
}
두번째풀이
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit) {
int answer = 0;
int num=0;
int head=0; int tail=people.size()-1;
sort(people.begin(),people.end());
while(head<=tail){
if(people[head]+people[tail]<=limit){
head+=1;
tail-=1;
answer+=1;
}
else{
tail--;
answer+=1;
}
}
return answer;
}
'Algorithm > 프로그래머스' 카테고리의 다른 글
[프로그래머스] Level.2 해시- 위장 (0) | 2021.01.15 |
---|---|
[프로그래머스] Level.2 해시- 전화번호 목록 (0) | 2021.01.15 |
[프로그래머스] Level.2 힙(heap)- 더 맵게 (0) | 2021.01.14 |
[프로그래머스]Level.2 멀쩡한 사각형 (0) | 2021.01.14 |
[프로그래머스]Level.2 스택/큐-다리를 지나는 트럭 (0) | 2021.01.13 |