[코딩테스트]벡터 관련 문제 정리

정제철·2023년 5월 25일
0

알고리즘

목록 보기
5/12
post-thumbnail
  • answer.push_back(arr.at(i - 1)) => 가능
  • push_back(x.end()) => 불가능
  • x.begin(), x.end() -> 주소를 나타내기 때문에 직접 삽입은 못한다
  • 직접 삽입하려면
    -x.begin() -> x.front()
    -x.end -> x.back()
  • if (x.empty() == true)
    벡터x가 비어있는지, 들어있는지로 구할 수 있다.

1. 배열의 평균값

  • 문제 설명
    정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소의 평균값을 return하도록 solution 함수를 완성해주세요.

  • 제한사항
    0 ≤ numbers의 원소 ≤ 1,000
    1 ≤ numbers의 길이 ≤ 100
    정답의 소수 부분이 .0 또는 .5인 경우만 입력으로 주어집니다.

  • 입출력 예
    numbers result
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = 5.5
    [89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] = 94.0

내코드

#include <string>
#include <vector>

using namespace std;

double solution(vector<int> numbers) {
    double answer = 0;
    for(auto i : numbers)
    {
        answer+=i;
    }
    return answer/numbers.size();
}

우수풀이

#include <string>
#include <vector>
#include <numeric>
using namespace std;

double solution(vector<int> numbers) {
    double answer = 0;
    int sum = accumulate(begin(numbers), end(numbers), 0, plus<int>());
    answer = (double)sum / numbers.size();
    return answer;
}

2. 배열 원소의 길이

  • 문제 설명
    문자열 배열 strlist가 매개변수로 주어집니다. strlist 각 원소의 길이를 담은 배열을 retrun하도록 solution 함수를 완성해주세요.

  • 제한사항
    1 ≤ strlist 원소의 길이 ≤ 100
    strlist는 알파벳 소문자, 대문자, 특수문자로 구성되어 있습니다.

  • 입출력 예
    strlist : result
    ["We", "are", "the", "world!"][2, 3, 3, 6]
    ["I", "Love", "Programmers."][1, 4, 12]

내풀이=우수풀이

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<string> strlist) {
    vector<int> answer;
    for(auto i : strlist)
    {
        answer.push_back(i.length());
    }
    return answer;
}

3. 배열 뒤집기

  • 문제 설명
    정수가 들어 있는 배열 num_list가 매개변수로 주어집니다. num_list의 원소의 순서를 거꾸로 뒤집은 배열을 return하도록 solution 함수를 완성해주세요.

  • 제한사항
    1 ≤ num_list의 길이 ≤ 1,000
    0 ≤ num_list의 원소 ≤ 1,000

  • 입출력 예
    num_list -> result
    [1, 2, 3, 4, 5][5, 4, 3, 2, 1]
    [1, 1, 1, 1, 1, 2][2, 1, 1, 1, 1, 1]
    [1, 0, 1, 1, 1, 3, 5][5, 3, 1, 1, 1, 0, 1]

- 내풀이

for(int i =0; i<num_list.size();i++)
{
    answer.push_back(num_list.back());
    num_list.pop_back();
}

for(int i =0; i<num_list.size();i++)로 반복문을 작성했는데
num_list.pop_back();의 영향으로 반복문의 끝지점에 있는 벡터의 값이 줄어들어서 5개의 값이 들어있는 배열이 출력되어야하는데 3개만 출력되는 문제를 겪었다.
그래서 문제인 부분만 주석처리를 했는데 5개의 값을 가진 배열로 출력되었다.
그렇기 때문에 그 부분이 문제라고 판단하여 풀어냈다.
그래서 조건문의 끝지점 을 따로 x라고 변수화하여 고정시켰다.

#include <vector>

using namespace std;

vector<int> solution(vector<int> num_list) {
    vector<int> answer;
    int x=num_list.size();
    for(int i =0; i<x;i++)
    {
        answer.push_back(num_list.back());
        num_list.pop_back();
    }
    return answer;
}

- 우수풀이

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

using namespace std;

vector<int> solution(vector<int> num_list) {
    vector<int> answer;
    reverse(num_list.begin(), num_list.end());

    return num_list;
}

- 정석풀이

int i = 배열의 길이-1 ; i가 = 0이 될때까지 i를 뺀다.
이는 (int i = 0; i < 배열의 길이; i++ )와 같다.
배열의 인덱스를 구해야 하기때문에 -1씩 해준다.
뒤의 값부터 answer에 담는다.

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> num_list) {
    vector<int> answer;
    for(int i = num_list.size()-1; i >= 0; i--){
        answer.push_back(num_list[i]);
    }
    return answer;
}

4. 배열 자르기

  • 문제 설명
    정수 배열 numbers와 정수 num1, num2가 매개변수로 주어질 때, numbers의 num1번 째 인덱스부터 num2번째 인덱스까지 자른 정수 배열을 return 하도록 solution 함수를 완성해보세요.

  • 제한사항
    2 ≤ numbers의 길이 ≤ 30
    0 ≤ numbers의 원소 ≤ 1,000
    0 ≤num1 < num2 < numbers의 길이

  • 입출력 예
    numbers / num1 /num2 -> result
    [1, 2, 3, 4, 5] /1/ 3 -> 2, 3, 4
    [1, 3, 5] /1 /2 -> [3, 5]

- 내풀이

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> numbers, int num1, int num2) {
    vector<int> answer;
    for(int i = num1;i<=num2;i++ )
    {
        answer.push_back(numbers.at(i));
    }
    return answer;
}

- 정석풀이

#include <vector>

using namespace std;

vector<int> solution(vector<int> numbers, int num1, int num2) {
    vector<int> answer;
    answer.assign(numbers.begin()+num1, numbers.begin()+num2+1);
    return answer;
}

5. 벡터 정렬

  • 문제 설명
    선분 세 개로 삼각형을 만들기 위해서는 다음과 같은 조건을 만족해야 합니다.

가장 긴 변의 길이는 다른 두 변의 길이의 합보다 작아야 합니다.

삼각형의 세 변의 길이가 담긴 배열 sides이 매개변수로 주어집니다. 세 변으로 삼각형을 만들 수 있다면 1, 만들 수 없다면 2를 return하도록 solution 함수를 완성해주세요.

  • 제한사항
    sides의 원소는 자연수입니다.
    sides의 길이는 3입니다.
    1 ≤ sides의 원소 ≤ 1,000

  • 입출력 예
    sides result
    [1, 2, 3] 2
    [3, 6, 2] 2
    [199, 72, 222] 1

- 내풀이

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

using namespace std;

int solution(vector<int> sides) {
    int answer = 0;

	sort(sides.begin(), sides.end());
    if(sides[2]<sides[0]+sides[1]) return 1;
    else return 2;
}
profile
성공의 반대는 실패가 아닌 도전하지 않는 것이다.

0개의 댓글