zoukankan      html  css  js  c++  java
  • [leetcode sort]75. Sort Colors

    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.

    解法1:

    统计每个颜色出现的次数,这个方法比较简单易懂

     1 class Solution(object):
     2     def sortColors(self, nums):
     3         flag = [0,0,0]
     4         for i in nums:
     5             flag[i] += 1
     6         for n in range(flag[0]):
     7             nums[n] = 0
     8         for n in range(flag[1]):
     9             nums[flag[0]+n]=1
    10         for n in range(flag[2]):
    11             nums[flag[0]+flag[1]+n] = 2

    解法2:

    在评论区总是能发现一些很漂亮的方法,方法和快排比较相似

     1 class Solution(object):
     2     def sortColors(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: void Do not return anything, modify nums in-place instead.
     6         """
     7         i,start,end = 0,0,len(nums)-1
     8         while i<=end:
     9             if nums[i]==0:
    10                 nums[i]=nums[start]
    11                 nums[start]=0
    12                 start += 1
    13             elif nums[i]==2:
    14                 nums[i]=nums[end]
    15                 nums[end]=2
    16                 end -= 1
    17                 i -= 1 #交换后此位置的数未考虑,要重新考虑
    18             i += 1

    解法3:

    最帅的是这种方法,类似于快排,指针i,j分别处理以类数据

     1 class Solution(object):
     2     def sortColors(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: void Do not return anything, modify nums in-place instead.
     6         """
     7         i,j = 0,0
     8         for k in range(len(nums)):
     9             v = nums[k]
    10             nums[k] = 2
    11             if v<2:
    12                 nums[j]=1
    13                 j += 1
    14             if v == 0:
    15                 nums[i]=0
    16                 i += 1
  • 相关阅读:
    !!!C#——进制转换!
    冒泡排序后用二分查找法查找位置
    简陋的4位验证码程序(范围内取随机数)
    这个年龄计算程序相当不科学,体验还是差差哒
    8.7课堂随笔
    字符串中查询关键字
    !汉企的WiFi网速好快
    重度强迫症患者的九九乘法表
    自选数字和范围的整除算法
    day52
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6511535.html
Copyright © 2011-2022 走看看