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

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

그냥 행렬의 덧셈이다.

벡터를 생성과 동시에 초기화하면 capacity가 변하지 않는다.

 

fill constructor (벡터 생성자 초기화)

각 원소에 할당된 값이 있는 n개의 원소를 가진 컨테이너를 생성합니다.

 

시간 복잡도

O(n)

 

선언

vector<자료형> 컨테이너이름(n, value);

n 컨테이너의 크기

value 컨테이너의 각 원소에 할당될 값



출처: https://woodforest.tistory.com/206 [나무 숲]

프로그래머스 레벨 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
#include <string>
#include <vector>
 
using namespace std;
 
vector<int> solution(vector<int> arr) 
{
    int Min = arr[0];
    int Index = 0;
    
    if(arr.size() == 1)
    {
        arr[0= -1;
        return arr;
    }
    
    for(int i = 1 ; i < arr.size() ; i++)
    {
        Index = (Min > arr[i]) ? i : Index;
        Min = min(Min, arr[i]);
    }
    
    arr.erase(arr.begin() + Index);
    
    return arr;
}
 

algorithm 헤더에는 배열에서 가장 작은 값과 가장 큰 값을 찾아주는 함수가 있다.

min_element(), max_element()이다.

min_element(배열시작, 배열끝); 으로 사용하며, 반환값은 값이 들어있는 주소다.

 

min_element()를 알게되고 수정한 것

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
vector<int> solution(vector<int> arr) 
{
    vector<int>::iterator iter = arr.begin();    
    
    iter = min_element(arr.begin(), arr.end());
    arr.erase(iter);
    
    if(arr.empty())
        arr.emplace_back(-1);
    
    return arr;
}
 

min_element()와 이터레이터(반복자)를 이용해 이렇게 풀어낼수도 있다.

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

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
long long solution(long long n) 
{
    long long answer = 0;
    vector<int> vecAnswer;
    string str = to_string(n);
    
    for(int i = 0 ; i < str.size() ; i++)
        vecAnswer.emplace_back(str[i] - '0');
    
    sort(vecAnswer.begin(), vecAnswer.end());
    
    for(int i = 0 ; i < vecAnswer.size() ; i++)
        answer += vecAnswer[i] * pow(10, i);
        
    return answer;
}
 

내림차순 정렬 후 벡터의 순서대로 pow를 이용해 정답에 집어 넣었다.

+ Recent posts