ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม arr ซึ่งเรียงเพิ่มขึ้นแล้ว
ฟังก์ชันควรคืนอาร์เรย์ของกำลังสองของแต่ละตัวเลข เรียงเพิ่มขึ้นเช่นกัน
ตัวอย่างเช่น หากอินพุตคือ
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 ]