-
[JS 알고리즘&자료구조] 다중 포인터 패턴 : 또 다른 문제 풀이JavaScript/Basic 2023. 11. 13. 23:54
두 번째 문제를 살펴보도록 하자. countUniqueValues라는 함수는 전달된 정렬된 배열에 있는 고유한 값의 개수를 반환한다. 어떠한 숫자도 존재하지 않는 배열이라면 0을 반환한다. 해당 문제에 대한 나의 풀이이다.
function countUniqueValues(arr) { if(arr.length < 1) return 0; let i = 0; let j = 1; while(j < arr.length) { if (arr[i] !== arr[j]) { i++; arr[i] = arr[j]; } j++; } return i + 1; }
아래는 강의에서 소개하는 해결 방법이다.function countUniqueValues(arr) { if(arr.length < 1) return 0; let i = 0; for (let j = 0; j < arr.length; j++) { if (arr[i] !== arr[j]) { i++; arr[i] = arr[j]; } } return i + 1; }
나는 while문을 사용했고 강의의 풀이에서는 for문을 사용했다는 것을 제외하면 둘의 풀이는 거의 일치한다. (뿌-듯 😊)'JavaScript > Basic' 카테고리의 다른 글
[JS 알고리즘&자료구조] 다중 포인터 패턴 (0) 2023.11.13 [JS 알고리즘&자료구조] 빈도수 세기 : 애너그램 도전 과제 (0) 2023.11.07 [JS 알고리즘&자료구조] 빈도수 세기 패턴 (0) 2023.11.03 [JS 알고리즘&자료구조] 문제 해결 패턴 소개 (0) 2023.11.02 [JS 알고리즘&자료구조] 되돌아보기와 리팩터 (0) 2023.11.02