<문제소개>
- 문제명 : 체육복
- 사이트 : 프로그래머스
- 난이도 : level 1
- 사용 언어 : javascript
<문제 풀이>
접근 방식
- 여벌의 체육복이 있는데 도난당한 학생의 경우 lost와 reserve 모두에서 제외한다.
(입을 체육복이 있으나 더이상 빌려줄 수 없기 때문) - lost 각각의 요소에 +1, -1을 한 값이 reserve에 있는지 확인하고
있으면 체육복이 없는 학생 수 - 1, 일치하는 reserve 값을 reserve에서 제거
<내 코드>
function solution(n, lost, reserve) {
let students = n;
const realReserve = [];
reserve.forEach((res) => {
if (lost.indexOf(res) === -1) {
realReserve.push(res);
} else {
lost.splice(lost.indexOf(res), 1);
}
});
let noClothStudents = lost.length;
for (let i = 0; i < lost.length; i++) {
if (realReserve.indexOf(lost[i] - 1) !== -1) {
realReserve.splice(realReserve.indexOf(lost[i] - 1), 1);
noClothStudents--;
} else if (realReserve.indexOf(lost[i] + 1) !== -1) {
realReserve.splice(realReserve.indexOf(lost[i] + 1), 1);
noClothStudents--;
}
}
return students - noClothStudents;
}
<보완할 점>
- 어떤 배열을 반복문으로 돌릴 때 조건에 따라 해야하는 작업이 배열의 요소를 제거 또는 추가해야하는 경우
배열이 변화하면 조건이 제대로 동작하지 않을 수 있다.
→ 배열이 변화하지 않도록 하거나, 배열의 변화와 상관없이 작동하도록 만들어야한다.
- 배열에 원소가 포함되어있는지 확인하고싶을 때
arr.indexOf(item) !== -1
로 찾기보다
arr.includes(item) (=true / false)
로 조건을 검사하자.
'Programming' 카테고리의 다른 글
[Data Structure] Linked List (0) | 2021.06.16 |
---|---|
[React] 리액트 패키지 body-parser 사용시 취소선 해결 방법 (0) | 2021.06.04 |
[React] 리액트란? 리액트의 4가지 특성 (0) | 2021.06.02 |
[Algorithm] 프로그래머스 - level1 <신규아이디 추천> (0) | 2021.05.27 |
[Algorithm] 프로그래머스 - level1 <모의고사> (0) | 2021.05.26 |