“”“此為跟隨@ 代碼隨想錄19th訓練營之學習進度,
感謝Carl大神提供如此豐富的學習教材”“”
977. Squares of a Sorted Array
重點
- 該題提供一個non-decreasing order (非遞減排序)list,然後也要求return結果也要是non-decreasing order
- 該題也是鍛鍊如何使用雙指針的思維
代碼
暴力法
# brute force // time complexity O(nlogn)
def sortedSquares(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums[i] = nums[i]**2
return sorted(nums)
雙指針法
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
# two point // time complexity O(n)
left, right,i = 0, len(nums)-1, len(nums)-1
result = [0]*len(nums)
while left <= right:
if nums[left]**2 < nums[right]**2:
result[i] = nums[right]**2
right -= 1
else:
result[i] = nums[left]**2
left += 1
i -= 1
return result
5 thoughts on “(Leetcode) Array – part 2”
Actually when someone doesn’t know then its up to other users that they will assist, so here it happens.
Hey! Would you mind if I share your blog with my zynga
group? There’s a lot of people that I think would really enjoy your
content. Please let me know. Thanks
I every time emailed this website post page to all my contacts,
since if like to read it next my contacts will too.
Amazing! Its truly amazing post, I have got much clear
idea concerning from this article.
Definitely believe that which you said. Your favorite justification seemed to
be on the internet the easiest thing to be aware of.
I say to you, I definitely get irked while people consider worries that they just don’t know about.
You managed to hit the nail upon the top and
defined out the whole thing without having side effect , people could take a signal.
Will probably be back to get more. Thanks