Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 87ff2a6

Browse files
committed
add 977 solution
1 parent 9fb7252 commit 87ff2a6

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

977 - Squares Of A Sorted Array.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# 977 - Squares Of A Sorted Array
2+
3+
Difficulty: easy
4+
Done: No
5+
Last edited: February 17, 2022 12:47 PM
6+
Topic: two pointers
7+
8+
## Problem
9+
10+
Given an integer array `nums` sorted in **non-decreasing** order, return *an array of **the squares of each number** sorted in non-decreasing order*.
11+
12+
Example 1:
13+
14+
```
15+
Input: nums = [-4,-1,0,3,10]
16+
Output: [0,1,9,16,100]
17+
Explanation: After squaring, the array becomes [16,1,0,9,100].
18+
After sorting, it becomes [0,1,9,16,100].
19+
20+
```
21+
22+
Example 2:
23+
24+
```
25+
Input: nums = [-7,-3,2,3,11]
26+
Output: [4,9,9,49,121]
27+
28+
```
29+
30+
Constraints:
31+
32+
- `1 <= nums.length <= 104`
33+
- `104 <= nums[i] <= 104`
34+
- `nums` is sorted in **non-decreasing** order.
35+
36+
## Solution
37+
38+
lorem ipsum
39+
40+
## Whiteboard
41+
42+
[http://excalidraw.com](http://excalidraw.com)
43+
44+
## Code
45+
46+
```python
47+
class Solution:
48+
def sortedSquares(self, nums: List[int]) -> List[int]:
49+
return sorted([x**2 for x in nums])
50+
```
51+
52+
using built-in sorted
53+
54+
```python
55+
class Solution:
56+
def sortedSquares(self, nums: List[int]) -> List[int]:
57+
left, right = 0, len(nums)-1
58+
59+
while left <= right:
60+
61+
max_abs = max(nums[left:], key=abs)
62+
63+
nums.insert(0, nums.pop(nums.index(max_abs)))
64+
nums[0] = nums[0]**2
65+
left += 1
66+
67+
return nums
68+
```
69+
70+
custom 2 pointer approach

977.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def sortedSquares(self, nums):
3+
left, right = 0, len(nums)-1
4+
5+
stack = []
6+
7+
while left <= right:
8+
max_abs = max(nums, key=abs)
9+
nums.remove(max_abs)
10+
stack.insert(0, abs(max_abs)**2)
11+
left += 1
12+
13+
return stack
14+
15+
16+
if __name__ == '__main__':
17+
s = Solution()
18+
s.sortedSquares(nums = [-3, -3, 0,0, 1, 10])

0 commit comments

Comments
 (0)