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 
                        
                    
  • 相关阅读:
    电子公文传输系统个人贡献
    第十三章学习笔记
    第十二章学习笔记
    第14章学习笔记
    团队作业(五):冲刺总结
    冲刺总结(day7)
    thread同步测试
    冲刺总结(day1)
    元宇宙、VR(Unity3D、Unreal4)、AR、WPF&H5外包团队—北京动点飞扬软件新办公室照片
    kanzi外包团队:长年承接kanzi项目应用开发 Kanzi 3.6 LTS已经更新至3.6.3版!
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4567136.html
Copyright © 2011-2022 走看看