zoukankan      html  css  js  c++  java
  • 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.

    click to show follow up.

    Follow up:
    A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

    Could you come up with an one-pass algorithm using only constant space?

    首先复习一下基础知识:

    1,类的实例化: inst=className();即类名+(),如本题,实例化方法为:inst=Solution()

    2,if...eles if的表达方式不是c++那种表达方式,eles  if在python中表述为elif

    3,python有严格的缩进要求,不然就会报错,及时是使用注释'''或#也要缩进

    程序测试的时候,当测试数组为[2]的时候,报错while nums[end]==2: list index out of range,可我感觉下标没错,还需要认真的检查一下吧,

    为了避免这个问题,我加了了 if lenth==1。

    class Solution:
        # @param {integer[]} nums
        # @return {void} Do not return anything, modify nums in-place instead.
        def sortColors(self, nums):
            lenth=len(nums)
            start=0
            end=lenth-1
            while nums[start]==0:
                start+=1
                if start==lenth:
                    return 
                
            movePs=start
            while nums[end]==2:
                if end==0:
                    return
                end-=1
            while movePs<=end:
                if nums[movePs]==0:
                    temp=nums[start]
                    nums[start]=nums[movePs]
                    nums[movePs]=temp
                    start+=1
                    movePs+=1
                elif nums[movePs]==1:                     
                    movePs+=1
                else:
                    '''这是等于2的情况'''
                    temp=nums[end]
                    nums[end]=nums[movePs]
                    nums[movePs]=temp
                    end-=1
            return 
                        
                    
  • 相关阅读:
    欧几里德算法
    int 和 string 相互转换(简洁版)
    骆驼吃香蕉
    链表反转 (Multi-method)
    二分查找 (最经典代码,及其边界条件的实践分析)
    mottoes
    欧拉函数,欧拉定理,费马小定理。
    深搜和广搜的对比
    Python基础
    马拉车求最大回文字串
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4567136.html
Copyright © 2011-2022 走看看