
내가 처음 작성했던 코드는 아래와 같다.
public class Solution {
public int[] solution(int []arr) {
Stack<Integer> stack = new Stack<>();
int[] answer;
int temp = arr[0];
stack.push(temp);
for (int i = 1; i < arr.length; i++) {
if (temp != arr[i]) {
temp = arr[i];
stack.push(temp);
}
}
answer = new int[stack.size()];
for (int i = 0; i < stack.size(); i++)
answer[stack.size() - i - 1] = stack.pop();
return answer;
}
}
stack을 이용해 풀어보았다.
arr[0]을 temp 변수에 넣고,
temp을 stack에 넣은 뒤
arr을 순회하면서 temp와 값이 다르면 그 값을 temp에 넣고 다시 stack에 push하는 방식이다.
문제를 잘 해결했다고 생각했는데,
코드를 실행시켜보면 stack.size()가 4여서 answer의 길이가 4가 됐음에도 불구하고
return 직전의 for문은 2번 밖에 안돌아가는 걸 확인할 수 있었다.
그 이유는 내가 return 직전에 있는 for문의 조건을 i가 stack.size()보다 작을 때라고 해놨는데,
for문 안에서 stack.pop()을 해주니까 stack.size()가 계속 바뀌는 것이었다.
나는 그걸 미쳐 생각하지 못하고 stack.size()는 계속 4일 것이라고 생각했다..
문제를 발견했으니 해결방법은 간단했다.
size 변수를 선언한 뒤 stack.size()을 넣어주면 size의 값은 계속 고정돼있을 것이다.
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
Stack<Integer> stack = new Stack<>();
int[] answer;
int temp = arr[0];
stack.push(temp);
for (int i = 1; i < arr.length; i++) {
if (temp != arr[i]) {
temp = arr[i];
stack.push(temp);
}
}
int size = stack.size();
answer = new int[size];
for (int i = 0; i < size; i++)
answer[size - i - 1] = stack.pop();
return answer;
}
}
아래와 같이 size 변수를 따로 선언해주지 않고 answer.length을 이용해줘도 괜찮겠다는 생각이 든다.
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
Stack<Integer> stack = new Stack<>();
int[] answer;
int temp = arr[0];
stack.push(temp);
for (int i = 1; i < arr.length; i++) {
if (temp != arr[i]) {
temp = arr[i];
stack.push(temp);
}
}
answer = new int[stack.size()];
for (int i = 0; i < answer.length; i++)
answer[answer.length - i - 1] = stack.pop();
return answer;
}
}
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] #134240 푸드 파이트 대회 (0) | 2024.08.24 |
---|---|
프로그래머스 #42586 기능개발 (0) | 2024.08.19 |
프로그래머스 #12948 핸드폰 번호 가리기 (0) | 2024.08.12 |
프로그래머스 #12981 영어 끝말잇기 (0) | 2024.08.06 |
프로그래머스 #12916 문자열 내 p와 y의 개수 (0) | 2024.08.02 |