[HAI] week3 two optimize solution remove reverse

https://leetcode.com/problems/squares-of-a-sorted-array/
This commit is contained in:
2024-12-05 22:30:37 +03:00
parent 35c77a3a23
commit 8dcb175459
2 changed files with 49 additions and 11 deletions
+20 -1
View File
@@ -32,6 +32,26 @@ Constraints:
## тест кейсы ## тест кейсы
```ts
describe("isPalindrome", () => {
it("A man, a plan, a canal: Panama => true", () => {
expect(isPalindrome("A man, a plan, a canal: Panama")).toBeTruthy();
});
it("race a car => false", () => {
expect(isPalindrome("race a car")).toBeFalsy();
});
it(" _ => true", () => {
expect(isPalindrome(" ")).toBeTruthy();
});
it(" 0P => false", () => {
expect(isPalindrome("0P")).toBeFalsy();
});
});
```
## текстовое описание решения ## текстовое описание решения
- я заведу два указателя которые поставлю в начало и в конец и буду двигаться в цикле пока эти указатели не пересекуться - я заведу два указателя которые поставлю в начало и в конец и буду двигаться в цикле пока эти указатели не пересекуться
@@ -101,4 +121,3 @@ function isPalindrome(s: string): boolean {
return true; return true;
}; };
``` ```
+29 -10
View File
@@ -1,20 +1,39 @@
// 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[] { export function sortedSquares(nums: number[]): number[] {
const result: number[] = []; const result: number[] = Array(nums.length).fill(0);
let L = 0; let L = 0;
let R = nums.length - 1; let R = nums.length - 1;
let indexResult = result.length - 1;
while (result.length !== nums.length) { while (L <= R) {
let leftValue = Math.pow(nums[L], 2); let leftValue = Math.pow(nums[L], 2);
let rightValue = Math.pow(nums[R], 2); let rightValue = Math.pow(nums[R], 2);
let resultValue = leftValue > rightValue ? leftValue : rightValue;
leftValue > rightValue ? L++ : R--;
if (leftValue > rightValue) { result[indexResult] = resultValue;
result.push(leftValue); indexResult--;
L++;
} else {
result.push(rightValue);
R--
}
} }
return result.reverse(); return result;
}; };