Day5-75. Sort Colors

今日题目:75. Sort Colors(Medium)

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]

Example 3:
Input: nums = [0]
Output: [0]

Example 4:
Input: nums = [1]
Output: [1]

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is 0, 1, or 2.

思路:

由头(i)和尾(j)开始两两比较,
j由後向前和i比较,
若j较i小,则ij交换
j全部比完後,则将向後移

My solution

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        i=0
    
        for i in range(n):
            for j in range(n-1,i,-1):
                while j>i and nums[j] < nums[i]:
                    temp = nums[i]
                    nums[i] = nums[j]
                    nums[j] = temp

Result

https://ithelp.ithome.com.tw/upload/images/20210920/20140843sAmHJjViEd.png


<<:  第 04 天 坚持刷题持续进步( leetcode 098 )

>>:  Day 5. 在设置Unity VR环境时遇到的问题,以及不存在的解法Q

Day 20 : 模型优化 - 训练後量化 Post Training Quantization

当我们训练模型需要部署在硬体较为受限的智慧型装置、IOT设备,模型运算在吃紧的硬体资源中显得笨重,...

创建App-自创简略帐号设定

创建App-自创简略帐号设定 由於App的最後设定界面的延伸界面没有设计与排版,因此考虑到学生相关的...

Day9-React Hook 篇-认识 useCallback

今天介绍的也是避免重新渲染,使 React 效能优化的 hook useCallback。 useC...

Python 演算法 Day 10 - Feature Selection

Chap.II Machine Learning 机器学习 https://yourfreetemp...

Day27 - [丰收款] 永丰线上收款支付API功能实作总结(3) - 如何让机敏性设定值更有保护力

在前一篇文章,我们分析了各个资安防护的强弱要点,但由於固定式的初始四Hash组代码是目前安全性最弱的...