문제
[프로그래머스] 같은 숫자는 싫어
https://school.programmers.co.kr/learn/courses/30/lessons/12906
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
코드 1 - 스택 사용
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(vector<int> arr) {
vector<int> answer;
stack<int> st;
for (int i = arr.size() - 1; i >= 0; i--) {
if (st.empty() || st.top() != arr[i])
st.push(arr[i]);
}
while (!st.empty()) {
answer.push_back(st.top());
st.pop();
}
return answer;
}
스택은 LIFO 구조이기 때문에 arr 배열의 마지막 원소부터 스택에 push하고 나중에 스택의 top 원소부터 차례로 꺼내야 한다.
코드 2 - 스택 사용 안 함
#include <vector>
using namespace std;
vector<int> solution(vector<int> arr) {
vector<int> answer;
int last = -1;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] != last) {
answer.push_back(arr[i]);
last = arr[i];
}
}
return answer;
}
이건 그냥 last 변수를 -1로 초기화하고, arr의 첫번째 원소부터 last와 비교해가며 last와 같지 않으면 answer에 넣고 last 값을 갱신하는 단순한 풀이이다.
두 코드 모두 정확성과 효율성에서 같은 점수를 얻었다.
스택은 LIFO 구조임을 유의!!
'99클럽 TIL' 카테고리의 다른 글
99클럽 코테 스터디 17일차 TIL + 스택/큐(C++) (6) | 2024.11.14 |
---|---|
99클럽 코테 스터디 16일차 TIL + 그리디(C++) (0) | 2024.11.12 |
99클럽 코테 스터디 14일차 TIL + 스택/큐(C++) (0) | 2024.11.11 |
99클럽 코테 스터디 13일차 TIL + 문자열 파싱(C++) (0) | 2024.11.09 |
99클럽 코테 스터디 12일차 TIL + BFS(C++) (0) | 2024.11.09 |