Given an array of integers nums, the array in ascending order.
Example 1:
Input: [5,2,3,1]
Output: [2,3,5]
Example 2:
Input: [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
prompt:
1 <= A.length <= 10000
-50000 <= A[i] <= 50000
Source: stay button (LeetCode) link: https: //leetcode-cn.com/problems/sort-list
Do merge sort method:
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
if len(nums)==1: #递归边界:数组长度为1时返回
return nums
mid = len(nums)//2 #递归一直分成两半,直到分成左右(1,1),或左右(1,2)or(2,1),则1的直接返回,2的再分成(1,1)
pre = nums[:mid]
tail= nums[mid:]
left = self.sortArray(pre)
right = self.sortArray(tail)
res = [] #用于装合并后的有序数组
while left and right: # 合并,左右(1,1)合并时,把小的装进去,大的由下面if装
if left[0]<=right[0]:
res.append(left.pop(0)) #left,right长大于1时,注意从第一个开始比
else:
res.append(right.pop(0)) #注意装完要轮空,不然会死循环
if left: #用来处理while后剩下的一个
res+=left
if right:
res+=right
return res
Merge the idea first been divided into two halves, and then merge sort. Incorporated by the following code portion while
Process Example 2:
[5,1,1,2,0,0]
Min [5,1,1] [2,0,0]
Min [5] [1, 1] [2] [0,0]
Min [5] [1] [1] [2] [0] [0]
Co [1,1] [0,0] # [1] is returned to the right and left [5] together entered while, right [0,0] and left [2] The same
Co [1,1,5] [0,0,2]
Together [0,0,1,1,2,5]
You can also write a single combined function:
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def marge(left, right):
res = []
while left and right:
# 左右两个数列第一个最小放前面
if left[0] <= right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
# 只有一个数列中还有值,直接添加
res += left
res += right
return res
if len(nums) == 1:
return nums
mid = len(nums) // 2
left = nums[:mid]
right = nums[mid:]
return marge(self.sortArray(left), self.sortArray(right))
With the experience of 912 questions, 148 is relatively easy:
Complexity and the spatial complexity of constant grade, are sorted linked list in O (n log n) time.
Example 1:
Input: 4-> 2-> 1-> 3
Output: 1-> 2-> 3-> 4
Example 2:
Input: -1-> 5-> 3-> 4-> 0
Output: -1-> 0-> 3-> 4-> 5
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next: # 链表为空的情况直接返回not head.next类似于数组长度为1
return head
slow = head #用快慢指针把链表分成两半
fast = head.next
while(fast and fast.next):
slow = slow.next
fast = fast.next.next
tmp = slow.next
slow.next = None #把前半部分的尾巴置空
left = self.sortList(head)
right = self.sortList(tmp)
cur = res = ListNode(0) #用一个新链表装排序后合并的部分
while left and right:
if left.val<=right.val:
cur.next = left
left = left.next #加入后置空或用下一位进入比较
else:
cur.next = right
right = right.next
cur = cur.next
cur.next = left or right #把while过后剩下的接上去
return res.next
Example two processes:
-1->5->3->4->0
分 -1->5 3->4->0
-1534- sub> 0
Min -15340
-1-> 530-> 4
合 -1->5 0->3->4
合 -1->0->3->4->5