반응형
https://programmers.co.kr/learn/courses/30/lessons/12906
코딩테스트 연습 - 같은 숫자는 싫어
배열 arr가 주어집니다. 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다. 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다. 단, 제거된 후 남은
programmers.co.kr
문제 접근법
2가지의 방식으로 풀 수 있습니다.
첫 번째
- for문을 통해 순회하면서 이전의 값과 비교합니다.
- 이전의 값과 같을 경우 계속 진행하고 이전의 값과 다를 경우 이전 값을 저장합니다.
- for문을 끝까지 돌았을 때 마지막 값을 저장해줍니다.
더보기
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
|
#include <vector>
using namespace std;
vector<int> solution(vector<int> arr)
{
vector<int> answer;
int len = arr.size();
int temp = arr[0];
int count = 0;
for (int i = 1; i < len; i++)
{
if (temp == arr[i])
{
temp = arr[i];
count++;
}
else
{
answer.push_back(temp);
temp = arr[i];
count = 0;
}
}
answer.push_back(arr[len - 1]);
return answer;
}
|
cs |
두 번째
vector의 erase와 algorithm 헤더의 uniqe를 이용하여 해결하는 방법입니다.
더보기
1
2
3
4
5
6
7
8
9
10
11
|
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> arr)
{
vector<int> answer;
arr.erase(unique(arr.begin(), arr.end()), arr.end());
return arr;
}
|
cs |
반응형
'프로그래머스 문제풀이 > LEVEL 1' 카테고리의 다른 글
[프로그래머스 / Level 1] 나누어 떨어지는 숫자 배열 (C++) (0) | 2021.11.17 |
---|---|
[프로그래머스 / Level 1] 가운데 글자 가져오기 (C++) (0) | 2021.11.17 |
[프로그래머스 / Level 1] 2016년 (0) | 2021.10.27 |
[프로그래머스 / Level 1] 크레인 인형뽑기 게임 (0) | 2021.10.27 |
[프로그래머스 / Level 1] 체육복 (0) | 2021.06.22 |