[ 알고리즘풀이 ]

 배에 두 명 밖에 못타므로, 투포인터를 이용해서 앞과 뒤에서 동시에 순회해주면 시간 안에 문제를 해결할 수 있다.

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> people, int limit) {
    int answer = 0;
    bool check[50000]={};
    sort(people.begin(), people.end());
    int i = 0, j = people.size() - 1;
    while(i < j){
        if(people[i] + people[j] <= limit){ // 짝을 찾음.
            check[i] = check[j] = true;
            i++, j--, answer++;
        }
        else{ // 짝못찾는경우 -> 혼자 배타야됨.
            j--;
            answer++;
        }
    }
    if(i == j) // 투포인터가 만나서 혼자배타야됨.
        answer++;
    
    return answer;
}

 

+ Recent posts