프로그래머스 레벨 1 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <string>
#include <vector>
 
using namespace std;
 
int solution(int n, vector<int> lost, vector<int> reserve) 
{
    int answer = n - lost.size();
    int iSize = reserve.size();
    
    //여벌을 가진사람중에 잃어버린 사람이 있는지
    for(auto& a : reserve)
    {
        for(auto& b : lost)
        {
            if(a==b)
            {
                answer++;
                a = -10;
                b = -1;
            }
        }
    }
    
    
    for(int i = 0 ; i < iSize ; i++)
    {
        
        for(int k = 0 ; k < lost.size() ; k++)
        {
            //여벌을 가진사람이 누구에게 빌려줄수
            if(reserve[i] -1 == lost[k] || reserve[i] +1 == lost[k])
            {
                answer++;
                reserve[i] = -10;
                lost[k] = -1;
            }
        }
    }
    
    
    return answer;
}
 

1. 전체 인원수에서 잃어버린 사람들의 수를 먼저 계산한다.

2. 여벌을 가진 목록과 잃어버린 사람 목록에 동일한 사람이 있는지 확인

3. 남은 사람들중 빌려줄 수 있는 체육복을 가진 사람을 확인

 

for문을 분리한 이유는 n = 10, lost = [3,9,10] reserve = [3,8,9]

같은 경우를 방지하기 위해서이다.

값을 수정한 이유는 삭제로인한 벡터의 재할당보다 값 변경이 싸게 먹힐거라 생각했기 때문이다.

 -> 벡터 컨테이너의 Capcity를 할당하면 삭제로 인한 재할당은 없을 것이다.

프로그래머스 레벨 1 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <algorithm>
 
using namespace std;
 
int solution(vector<int> d, int budget) {
    int answer = 0;
    int sum = 0;
    
    sort(d.begin(), d.end());
    
    for(int i = 0 ; i < d.size() ; i++)
    {
        if(sum + d[i] > budget)
            break;
        
        sum += d[i];
        answer++;
    }
    
    return answer;
}
 

알고리즘의 sort함수를 이용하면 쉽게 풀 수 있다.

프로그래머스 레벨 1 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <vector>
 
using namespace std;
 
vector<long long> solution(int x, int n) {
    vector<long long> answer;
    answer.reserve(n);
    
    for(int i = 0 ; i < n ; i++)
        answer.emplace_back(x * (i + 1));
    
    return answer;
}
 

굳이 포스팅할 문제는 아니지만, vector를 미리 reserve() 하고 사용하면, 컨테이너용량이 늘어날때 벡터의 capacity가 재할당 되기때문에 이를 방지한다는 것을 알리려고 포스팅했다.

+ Recent posts