Skip to content

Commit 775d7dd

Browse files
committed
Squares-of-a-Sorted-Array
1 parent df245d6 commit 775d7dd

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
3333
-[x][Contains Duplicate](Arrays/217-Contains-duplicate.py)
3434
-[x][Product Of Array Except Self](Arrays/238-product-of-array-except-self.py)
3535

36+
-[x][Two Pointers](Two-Pointers)
37+
-[x][Squares of a Sorted Array](Two-Pointers/977-Squares-of-a-Sorted-Array.py)
38+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"Leetcode- https://leetcode.com/problems/squares-of-a-sorted-array/ "
2+
'''
3+
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
4+
5+
Example 1:
6+
7+
Input: nums = [-4,-1,0,3,10]
8+
Output: [0,1,9,16,100]
9+
Explanation: After squaring, the array becomes [16,1,0,9,100].
10+
After sorting, it becomes [0,1,9,16,100].
11+
'''
12+
13+
# Solution 1
14+
defsortedSquares(self, nums):
15+
ans= []
16+
17+
foriinrange(len(nums)):
18+
ans.append(nums[i]*nums[i])
19+
i+=1
20+
21+
ans.sort()
22+
returnans
23+
24+
#T: O(NLOGN)
25+
#S: O(N)
26+
27+
# Solution 2 - Two Pointer
28+
defsortedSquares(self, nums):
29+
i=0
30+
j=len(nums)-1
31+
temp= []
32+
while(i<=j):
33+
ifnums[i]*nums[i] >nums[j]*nums[j]:
34+
temp.append(nums[i]*nums[i])
35+
i+=1
36+
else:
37+
temp.append(nums[j]*nums[j])
38+
j-=1
39+
returntemp.sort()
40+
41+
#T: O(N)
42+
#S: O(N)

0 commit comments

Comments
 (0)
close