https://school.programmers.co.kr/learn/courses/30/lessons/12906
문제 설명
배열 arr가 주어집니다. 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다. 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다. 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다. 예를 들면,
- arr = [1, 1, 3, 3, 0, 1, 1] 이면 [1, 3, 0, 1] 을 return 합니다.
- arr = [4, 4, 4, 3, 3] 이면 [4, 3] 을 return 합니다.
배열 arr에서 연속적으로 나타나는 숫자는 제거하고 남은 수들을 return 하는 solution 함수를 완성해 주세요.
제한 사항
- 배열 arr의 크기 : 1,000,000 이하의 자연수
- 배열 arr의 원소의 크기 : 0보다 크거나 같고 9보다 작거나 같은 정수
입출력 예
arr | answer |
[1,1,3,3,0,1,1] | [1,3,0,1] |
[4,4,4,3,3] | [4,3] |
해결 방법
1. 결과를 담을 빈 배열 result를 만든다.
2. arr[i]가 result 배열의 마지막 값과 같지 않다면 push 한다.
전체 코드
function solution(arr){
const result = [];
arr.forEach((e, index) => {
if(arr[index] !== result[result.length-1]){
result.push(arr[index]);
}
})
return result;
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[JavaScript] 프로그래머스 스택/큐 #기능개발 (0) | 2022.09.12 |
---|---|
[JavaScript] 프로그래머스 스택/큐 #올바른 괄호 (0) | 2022.09.09 |
[JavaScript] 프로그래머스 해시 #위장 (0) | 2022.09.08 |
[JavaScript] 프로그래머스 해시 #완주하지 못한 선수 (0) | 2022.09.02 |
[JavaScript] 프로그래머스 Level 1 #폰켓몬 (0) | 2022.09.01 |