找LeetCode上简单的题目来撑过30天啦(DAY10)

终於第十天了呀,我觉得要撑满30天好难,奇怪了我为甚麽要这麽勉强自己,压力爆棚压

题号: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.

我的程序码

void sortColors(int* nums, int numsSize){
    int i,f=0,s=0,t=0,temp=0;
    
    for(i=0;i<numsSize;i++){
        if(nums[i]==0){
            f++;
        }else if(nums[i]==1){
            s++;
        }else{
            t++;
        }
    }
    
    for(i=0;i<numsSize;i++){
        if(f!=0){
            nums[i] = 0;
            f--;
        }else if(s!=0){
            nums[i] = 1;
            s--;
        }else if(t!=0){
            nums[i] = 2;
            t--;
        }
    }
    return 0;
}

DAY10心得
这题一开始想用sort解决,但後来发现,要写sort还不如用无脑解,反正数字只有三种,先跑一轮计算各有几个,在把正确的数量依大小填回原本的阵列就解完了,最大的心得就是,不要小看无脑解,能达成目标的都是好解。


<<:  [铁人赛 Day10] Context(下)-花式用法

>>:  Day 10. slate × 架构蓝图

Day 19:怎麽在 Angular 专案中使用 nvm 切换 Node.js 版本

前一篇谈到了 Angular 版本如何更新的议题,今天依然讨论跟版本相关的议题:如何在 Angula...

滤镜-30天学会HTML+CSS,制作精美网站

前一章节介绍过混合模式,相信对滤镜也不会很陌生。「滤镜」是什麽呢?他可以做出与Photoshop相同...

【Day 25】用 SOLID 方式开发 React (2)

SOLID 介面隔离原则 (IIP, Interface Segregation Principle...

Day 20 - 利用路由软件将路由收进 VRF

昨天我们设定好 VRF 後,今天就来与大家分享怎麽样将 BGP 路由收进 VRF 内吧! 事前准备 ...

【Day03】Verilog 资料型态(上)

资料型态 值 意义 0 低电位(逻辑0) 1 高电位(逻辑1) Z 高阻抗(High Impende...