Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
比较简单,要是可以用库函数,python一句话就解决了
nums.sort()
归并排序:
class Solution(object):
def merge(self, list, l, m, r):
left = list[l:m+1]
right = list[m+1:r+1]
for i in range(l, r+1):
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
list[i] = left.pop(0)
else:
list[i] = right.pop(0)
elif len(left) == 0:
list[i] = right.pop(0)
elif len(right) == 0:
list[i] = left.pop(0)
def mergeSort(self, list, l, r):
if l < r:
m = (l+r)/2
self.mergeSort(list, l, m)
self.mergeSort(list, m+1, r)
self.merge(list, l, m, r)
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
#nums.sort()
self.mergeSort(nums, 0, len(nums)-1)
# return nums
快速排序
import sys
sys.setrecursionlimit(99999)
class Solution(object):
#快速排序
def partition(self, list, l, r):
x = list[r]
k = l
for i in range(l, r):
if list[i] <= x:
list[k], list[i] = list[i], list[k]
k += 1
list[k], list[r] = list[r], list[k]
# k += 1
return k
def quickSort(self, list, l, r):
if l < r:
m = self.partition(list, l, r)
self.quickSort(list, l, m-1)
self.quickSort(list, m+1, r)
def sortColors(self, nums):
self.quickSort(nums, 0, len(nums)-1)
若不加上
import sys
sys.setrecursionlimit(99999)
则会出现错误:maximum recursion depth exceeded.