- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path977-Squares-of-a-Sorted-Array.py
42 lines (34 loc) · 929 Bytes
/
977-Squares-of-a-Sorted-Array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"Leetcode- https://leetcode.com/problems/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].
'''
# Solution 1
defsortedSquares(self, nums):
ans= []
foriinrange(len(nums)):
ans.append(nums[i]*nums[i])
i+=1
ans.sort()
returnans
#T: O(NLOGN)
#S: O(N)
# Solution 2 - Two Pointer
defsortedSquares(self, nums):
i=0
j=len(nums)-1
temp= []
while(i<=j):
ifnums[i]*nums[i] >nums[j]*nums[j]:
temp.append(nums[i]*nums[i])
i+=1
else:
temp.append(nums[j]*nums[j])
j-=1
returntemp.sort()
#T: O(N)
#S: O(N)