Mô tả vấn đề
Chúng ta cần viết hàm JavaScript nhận vào mảng số nguyên arr đã sắp xếp tăng dần. Hàm trả về mảng bình phương của mỗi số, cũng sắp xếp tăng dần.
Ví dụ, nếu đầu vào là:
const arr = [-2, -1, 1, 3, 6, 8];
Thì đầu ra nên là:
const output = [1, 1, 4, 9, 36, 64];
Ví dụ minh họa
Mã thực hiện (hai con trỏ từ hai đầu):
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));Đầu ra
Kết quả trong console sẽ là:
[ 1, 1, 4, 9, 36, 64 ]