[HAI] week3 two pointers squares of a sorted array

https://leetcode.com/problems/squares-of-a-sorted-array/
main
Vasily Guzov 1 year ago
parent 78b50806e3
commit f16f797381

@ -0,0 +1,3 @@
import { sortedSquares } from "./sortedSquares";
export default sortedSquares;

@ -0,0 +1,33 @@
# sortedSquares
## описание задачи
## тест кейсы
## текстовое описание решения
## ассимптотическая оценка
| Description | Estimation |
| ----------- | ---------- |
| time: | O(n) |
| mem: | O(n) |
## time
| Description | Time |
| ------------------------------------------- | ----- |
| анализ и сбор информации | 00:00 |
| обдумываение решения и формулировка решения | 00:00 |
| имплементация | 00:00 |
| исправление ошибок | 00:00 |
| полное время затраченое на решение | 00:00 |
## журнал ошибок
## code
### typescript
ts

@ -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…
Cancel
Save