2023年10月27日 星期五

10/25 每日一題(將數組平方後, 使用O(n)時間解決排序 )

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

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

 

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

 

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach? 

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        0#雙指針
        n = len(nums)
        res= [0]*n
        left,right, index = 0, n-1, n-1

        while left <= right:
            left_squ = nums[left]**2
            right_squ = nums[right]**2
           
            if left_squ < right_squ:
                res[index] = right_squ
                right -= 1

            else:
               
                res[index] = left_squ
                left += 1
           
            index -= 1
        return res



        # stack = [i**2 for i in nums]
        # #使用插入排序法
        # for i in range(1,len(stack)):
           
        #     j = i
        #     print(f'i={i}, j={j}')
        #     while j > 0 and stack[j-1] >stack[j]:
        #         '出現前項比後項大的時候就交換'
       
        #         stack[j-1], stack[j] = stack[j], stack[j-1]
        #         j-=1
       
       
        return stack

       
       
       
       

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁