[HAI] week3 two optimize solution remove reverse
https://leetcode.com/problems/squares-of-a-sorted-array/
This commit is contained in:
@@ -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;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
@@ -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[] {
|
||||
const result: number[] = [];
|
||||
const result: number[] = Array(nums.length).fill(0);
|
||||
let L = 0;
|
||||
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 rightValue = Math.pow(nums[R], 2);
|
||||
let resultValue = leftValue > rightValue ? leftValue : rightValue;
|
||||
leftValue > rightValue ? L++ : R--;
|
||||
|
||||
if (leftValue > rightValue) {
|
||||
result.push(leftValue);
|
||||
L++;
|
||||
} else {
|
||||
result.push(rightValue);
|
||||
R--
|
||||
}
|
||||
result[indexResult] = resultValue;
|
||||
indexResult--;
|
||||
}
|
||||
|
||||
return result.reverse();
|
||||
return result;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user