문제
오름차순으로 정렬된 정수 배열 arr을 받는 JavaScript 함수를 작성해야 합니다.
우리 함수는 오름차순으로 정렬된 각 숫자의 제곱 배열을 반환해야 합니다.
예를 들어, 함수에 대한 입력이 -
인 경우const arr = [-2, -1, 1, 3, 6, 8];
그러면 출력은 다음과 같아야 합니다. -
const output = [1, 1, 4, 9, 36, 64];
예시
이에 대한 코드는 -
const arr = [-2, -1, 1, 3, 6, 8];
const findSquares = (arr = []) => {
const res = []
let left = 0
let right = arr.length - 1
while (left <= right) {
const leftSquare = arr[left] * arr[left]
const rightSquare = arr[right] * arr[right]
if (leftSquare < rightSquare) {
res.push(rightSquare)
right -= 1
} else {
res.push(leftSquare)
left += 1
}
}
return res.reverse();
};
console.log(findSquares(arr)); 출력
콘솔의 출력은 -
[ 1, 1, 4, 9, 36, 64 ]