leetcode 912 排序陣列

2021-09-29 20:37:49 字數 2882 閱讀 8881

給定乙個整數陣列 nums,將該陣列公升序排列。

示例 1:

輸入:[5,2,3,1]

輸出:[1,2,3,5]

示例 2:

輸入:[5,1,1,2,0,0]

輸出:[0,0,1,1,2,5]

1 <= a.length <= 10000

-50000 <= a[i] <= 50000

實際上python自帶的sort函式是最好的,用了timesort,時間複雜度是o(nlogn)。

用快排,平均時間複雜度是o(nlogn),最差的時間複雜度是o(n2)

用歸併,時間複雜度是o(nlogn)

快排:時間》62.34%

空間》100.00%

歸併:時間》70.21%

空間》100.00%

快排:

class

solution

(object):

defsortarray

(self, nums)

:"""

:type nums: list[int]

:rtype: list[int]

"""iflen

(nums)

<=1:

return nums

mid = nums[

len(nums)//2

] nums.remove(mid)

left, right =

,[]for each_num in nums:

if each_num < mid:

else

:return self.sortarray(left)

+[mid]

+ self.sortarray(right)

歸併:

class

solution

(object):

defsortarray

(self, nums)

:"""

:type nums: list[int]

:rtype: list[int]

"""return self.merge_sort(nums,0,

len(nums)-1

)def

merge

(self, nums, low, mid, high)

: merged_list =

left_p, right_p = low, mid +

1while left_p <= mid and right_p <= high:

if nums[left_p]

< nums[right_p]:)

left_p +=

1else:)

right_p +=

1while left_p <= mid:

) left_p +=

1while right_p <= high:

) right_p +=

1 nums[low:high +1]

= merged_list

defmerge_sort

(self, nums, low, high)

:if low == high:

return nums

mid =

(low + high)//2

self.merge_sort(nums, low, mid)

self.merge_sort(nums, mid +

1, high)

self.merge(nums, low, mid, high)

return nums

上面的歸併寫法其實在其他語言裡也適用,對鍊錶也適用,如果是對list的話,其實可以簡化成這樣:

class

solution

:def

merge_sorted_lists

(self, nums1:

list

, nums2:

list)-

>

list

: index1, index2 =0,

0 merged_list =

while index1 <

len(nums1)

and index2 <

len(nums2)

:if nums1[index1]

< nums2[index2]:)

index1 +=

1else:)

index2 +=

1if index1 <

len(nums1)

: merged_list += nums1[index1:

]if index2 <

len(nums2)

: merged_list += nums2[index2:

]return merged_list

defsortarray

(self, nums: list[

int])-

> list[

int]:if

len(nums)

<2:

return nums

mid =

len(nums)

>>

1return self.merge_sorted_lists(self.sortarray(nums[

:mid]

), self.sortarray(nums[mid:])

)

leetcode 912 排序陣列

這是乙個排序題,都是老生常談的東西了,之前用的排序演算法都是通過比較大小進行排序,貼一下不用比較大小的計數排序的 計數排序的思想是 對於陣列中乙個需要排序的數字x來說,算出陣列中小於等於它的數字個數便可得出該數在有序陣列中的位置。該演算法只適用於整數陣列,時間複雜度為o n k o n k o n ...

LeetCode 912 排序陣列

排序陣列 給你乙個整數陣列 nums,請你將該陣列公升序排列。class solution for int i 0 i nums.length i 如果沒有資料交換,說明已經完全有序,提前退出迴圈if flag return nums class solution 記錄最小值的索引 int min ...

LeetCode 912 排序陣列

difficulty 中等 給你乙個整數陣列nums,請你將該陣列公升序排列。示例 1 輸入 nums 5,2,3,1 輸出 1,2,3,5 示例 2 輸入 nums 5,1,1,2,0,0 輸出 0,0,1,1,2,5 1 nums.length 50000 50000 nums i 50000 ...