Algorithm/프로그래머스

[프로그래머스/C++] 두 개 뽑아서 더하기

pinevienna 2021. 2. 4. 01:38

 

 

입력된 배열에서 숫자를 무작위로 두 개 뽑아 더했을 때

나올 수 있는 모든 수를 중복 없이 벡터에 넣어 return 하는 문제

 

 

합은 이중 for문으로 모두 더하면 됨

bool형 배열을 만들어서 더할 때마다 값이 있는지 없는지 체크해줬다

없는 값이 나왔으면 answer에 push 해주면 된다

 

 

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
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
vector<int> solution(vector<int> numbers) {
    vector<int> answer;
    bool b[201= { false, };
    int sum;
 
    for (int i = 1; i < numbers.size(); i++) {
        for (int j = 0; j < i; j++) {
            sum = numbers[i] + numbers[j];
 
            if (b[sum] == false) {
                answer.push_back(sum);
                b[sum] = true;
            }
        }
    }
 
    sort(answer.begin(), answer.end());
    return answer;
}
cs

 

그런데 더 쉽게 푸는 사람이 있었다

set STL을 사용해서 풀기...

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
 
vector<int> solution(vector<int> numbers) {
    vector<int> answer;
    set<int> s;
 
    for (int i = 1; i < numbers.size(); i++) {
        for (int j = 0; j < i; j++) {
            s.insert(numbers[i] + numbers[j]);
        }
    }
 
    answer.assign(s.begin(), s.end());
    return answer;
}
cs

 

한 세 번째 기억하자고 다짐하는 것 같다.. set