문제링크
https://leetcode.com/problems/squares-of-a-sorted-array/
Squares of a Sorted Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
코드
풀이1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums)-1
ans = collections.deque()
while left<=right:
l,r = abs(nums[left]), abs(nums[right])
if l>r:
ans.appendleft(l*l)
left+=1
else:
ans.appendleft(r*r)
right-=1
return list(ans)
|
cs |

풀이2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums)-1
ans = [0]*len(nums)
while left<=right:
l,r = abs(nums[left]), abs(nums[right])
if l>r:
ans[right-left] = l*l
left+=1
else:
ans[right-left] = r*r
right-=1
return list(ans)
|
cs |
POINT
-풀이1:
0을 중심으로 좌 우가 대칭을 이루고 있으니, left pointer와 right pointer를 사용한다.
left pointer의 절대값과 right pointer의 절대값을 비교하여 더 큰 쪽을 deque()에 넣는다.
이때, collections.deque()의 함수 중 appendleft()를 사용하여 deque()에 추가하며
비내림차순(non-decreasing order)을 유지할 수 있다.
-풀이2:
deque()을 사용하지 않고 구현하기 위해선 미리 ans 리스트를 생성해두어야한다.
이후 풀이1과 마찬가지로 left pointer, right pointer의 절대값을 비교하여 더 큰 값을 ans에 추가시킨다.
이때 현재 채워야 할 인덱스는 right-left 로 표현할 수 있다.
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 283. Move Zeroes (0) | 2022.03.02 |
---|---|
[LeetCode] 189. Rotate Array (0) | 2022.03.01 |
[LeetCode] 35. Search Insert Position (0) | 2022.02.28 |
[LeetCode] 278. First Bad Version (2) | 2022.02.28 |
[LeetCode] 704. Binary Search (0) | 2022.02.28 |