(Leetcode) Array – part 2

“”“此為跟隨@ 代碼隨想錄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”

  1. 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

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

快速導覽