程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[leetcode question brushing Python] 977 Square of ordered array

編輯:Python

1 subject

Here's a button Non decreasing order Sorted array of integers nums, return The square of each number A new array of , According to the requirements Non decreasing order Sort .

2 analysis

(1) Method 1 : Use python Built in sort The fast line of
Spatial complexity O(n), Time complexity O(nlogn)
(2) Method 2
Direct insert sort , But the time limit is exceeded
Time complexity O ( n 2 ) O(n^2) O(n2), Time complexity O(1)
(3) Method 3
Double pointer
Time complexity O(n), Spatial complexity O(n)




3 python Realization

(1) Method 1

# Quick sort 
def sortedSquares(self, nums: List[int]) -> List[int]:
res = []
for i in nums:
res.append(i*i)
# The first method , Use python Built in sort Method 
res.sort()
# The second method , Write your own fast algorithm 
self.QuckSort(res,0,len(nums)-1)
return res
def partition(self,arr,low,high):
i = low-1
pivot =arr[high]
for j in range(low,high):
if arr[j]<=pivot:
i+=1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return i+1
def QuckSort(self,arr,low,high):
if low <high:
p = self.partition(arr,low,high)
self.QuckSort(arr,low,p-1)
self.QuckSort(arr,p+1,high)

(2) Method 2

 # Direct insert sort ; Be careful , Beyond the time limit 
def sortedSquares(self, nums: List[int]) -> List[int]:
if len(nums)==0:
return nums
nums[0] = nums[0]*nums[0]
for i in range(1,len(nums)):
temp = nums[i]*nums[i]
j=i-1
while j>=0 and temp<nums[j]:
nums[j+1] =nums[j]
j -=1
nums[j+1] = temp
return nums

(3) Method 3

# Double pointer 
def sortedSquares(self, nums: List[int]) -> List[int]:
if len(nums)==1:
return [nums[0]*nums[0]]
res = [-1]*len(nums)
idx = len(nums)-1
right =len(nums)-1
left = 0
while left<=right:
if nums[left]*nums[left]>nums[right]*nums[right]:
res[idx] = nums[left]*nums[left]
left +=1
else:
res[idx] = nums[right]*nums[right]
right -=1
idx -=1
return res

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved