You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
972 B
TypeScript
40 lines
972 B
TypeScript
// export function sortedSquares(nums: number[]): number[] {
|
|
// const result: number[] = [];
|
|
// let L = 0;
|
|
// let R = nums.length - 1;
|
|
|
|
// while (result.length !== nums.length) {
|
|
// let leftValue = Math.pow(nums[L], 2);
|
|
// let rightValue = Math.pow(nums[R], 2);
|
|
|
|
// if (leftValue > rightValue) {
|
|
// result.push(leftValue);
|
|
// L++;
|
|
// } else {
|
|
// result.push(rightValue);
|
|
// R--
|
|
// }
|
|
// }
|
|
|
|
// return result.reverse();
|
|
// };
|
|
|
|
export function sortedSquares(nums: number[]): number[] {
|
|
const result: number[] = Array(nums.length).fill(0);
|
|
let L = 0;
|
|
let R = nums.length - 1;
|
|
let indexResult = result.length - 1;
|
|
|
|
while (L <= R) {
|
|
let leftValue = Math.pow(nums[L], 2);
|
|
let rightValue = Math.pow(nums[R], 2);
|
|
let resultValue = leftValue > rightValue ? leftValue : rightValue;
|
|
leftValue > rightValue ? L++ : R--;
|
|
|
|
result[indexResult] = resultValue;
|
|
indexResult--;
|
|
}
|
|
|
|
return result;
|
|
};
|