[HAI] week3 two pointers squares of a sorted array
https://leetcode.com/problems/squares-of-a-sorted-array/main
parent
78b50806e3
commit
f16f797381
@ -0,0 +1,3 @@
|
||||
import { sortedSquares } from "./sortedSquares";
|
||||
|
||||
export default sortedSquares;
|
||||
@ -0,0 +1,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { sortedSquares } from "./sortedSquares.ts";
|
||||
|
||||
describe("sortedSquares", () => {
|
||||
it("[-4,-1,0,3,10] => [0,1,9,16,100]", () => {
|
||||
expect(sortedSquares([-4, -1, 0, 3, 10])).toEqual([0, 1, 9, 16, 100]);
|
||||
});
|
||||
|
||||
it("[-7,-3,2,3,11] => [4,9,9,49,121]", () => {
|
||||
expect(sortedSquares([-7, -3, 2, 3, 11])).toEqual([4, 9, 9, 49, 121]);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,20 @@
|
||||
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();
|
||||
};
|
||||
Loading…
Reference in New Issue