From 8d899dfe8f1d89d0afec2d005a9358af387251b0 Mon Sep 17 00:00:00 2001 From: Levy Date: Sun, 28 Apr 2024 22:42:48 +0800 Subject: [PATCH] 0977: Squares of a sorted array --- 0977-Squares_of_a_Sorted_Array/main.ts | 58 ++++++++++++++++++++++++ 0977-Squares_of_a_Sorted_Array/readme.md | 21 +++++++++ 2 files changed, 79 insertions(+) create mode 100644 0977-Squares_of_a_Sorted_Array/main.ts create mode 100644 0977-Squares_of_a_Sorted_Array/readme.md diff --git a/0977-Squares_of_a_Sorted_Array/main.ts b/0977-Squares_of_a_Sorted_Array/main.ts new file mode 100644 index 0000000..c63c21c --- /dev/null +++ b/0977-Squares_of_a_Sorted_Array/main.ts @@ -0,0 +1,58 @@ +// let nums = [-4, -1, 0, 3, 10]; +let nums = [-7, -3, 2, 3, 11]; + +function sortedSquaresByMapping(nums: number[]): number[] { + return nums.map((i) => i * i).sort((a, b) => a - b); +} + +function sortedSquaresFromTwoEnds(nums: number[]): number[] { + const ans = new Array(nums.length); + let left = 0, + right = nums.length - 1; + + for (let i = nums.length - 1; i >= 0; i--) { + if (Math.abs(nums[left]) > Math.abs(nums[right])) { + ans[i] = nums[left] * nums[left]; + left++; + } else { + ans[i] = nums[right] * nums[right]; + right--; + } + } + + return ans; +} + +function sortedSquaresByUnshifting(nums: number[]): number[] { + const ans: number[] = []; + let left = 0, + right = nums.length - 1; + + while (left <= right) { + if (Math.abs(nums[left]) > nums[right]) { + ans.unshift(nums[left] ** 2); + left++; + } else { + ans.unshift(nums[right] ** 2); + right--; + } + } + + return ans; +} + +console.time("sortedSquaresByMapping"); +let resultByMapping = sortedSquaresByMapping(nums); +console.timeEnd("sortedSquaresByMapping"); + +console.time("sortedSquaresFromTwoEnds"); +let resultFromTwoEnds = sortedSquaresFromTwoEnds(nums); +console.timeEnd("sortedSquaresFromTwoEnds"); + +console.time("sortedSquaresByUnshifting"); +let resultByUnshifting = sortedSquaresByUnshifting(nums); +console.timeEnd("sortedSquaresByUnshifting"); + +console.log(resultByUnshifting); +console.log(resultByMapping); +console.log(resultFromTwoEnds); diff --git a/0977-Squares_of_a_Sorted_Array/readme.md b/0977-Squares_of_a_Sorted_Array/readme.md new file mode 100644 index 0000000..1077e3f --- /dev/null +++ b/0977-Squares_of_a_Sorted_Array/readme.md @@ -0,0 +1,21 @@ +# 977. Squares of a Sorted Array + +Given an integer array `nums` sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. + +## Example 1: + +> Input: nums = [-4, -1, 0, 3, 10]
+> Output: [0, 1, 9, 16, 100]
+> Explanation: After squaring, the array becomes [16, 1, 0, 9, 100].
+> After sorting, it becomes [0, 1, 9, 16, 100]. + +## Example 2: + +> Input: nums = [-7, -3, 2, 3, 11]
+> Output: [4, 9, 9, 49, 121] + +## Constraints: + +- 1 <= nums.length <= 104 +- -104 <= nums[i] <= 104 +- `nums` is sorted in non-decreasing order.