leetcode:75. Sort Colors

21 篇文章 0 订阅

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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值