iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
AI & Data

想到甚麼打甚麼系列 第 10

找LeetCode上簡單的題目來撐過30天啦(DAY10)

  • 分享至 

  • xImage
  •  

終於第十天了呀,我覺得要撐滿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還不如用無腦解,反正數字只有三種,先跑一輪計算各有幾個,在把正確的數量依大小填回原本的陣列就解完了,最大的心得就是,不要小看無腦解,能達成目標的都是好解。


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY9)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY11)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言