์ƒˆ์†Œ์‹

IN DEPTH CAKE/Supercoder

[c++/LeetCode-Array] 75. Sort Colors

  • -
๋ฐ˜์‘ํ˜•

 

 

๋‚œ์ด๋„Medium

ํ‚ค์›Œ๋“œ: Array

 

 

๋ฌธ์ œ

์ฃผ์–ด์ง„ ๋ฐฐ์—ด nums์—๋Š” ๋นจ๊ฐ„์ƒ‰, ํฐ์ƒ‰ ๋˜๋Š” ํŒŒ๋ž€์ƒ‰์œผ๋กœ ์ƒ‰์น ๋œ n๊ฐœ์˜ ๊ฐ์ฒด๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋“ค์„ ๊ทธ ์ž๋ฆฌ์—์„œ ์ •๋ ฌํ•˜์—ฌ ๋™์ผํ•œ ์ƒ‰์ƒ์˜ ๊ฐ์ฒด๊ฐ€ ์„œ๋กœ ์ธ์ ‘ํ•˜๋„๋ก ๋งŒ๋“ญ๋‹ˆ๋‹ค. ์ด๋•Œ ์ƒ‰์ƒ์€ ๋นจ๊ฐ„์ƒ‰, ํฐ์ƒ‰ ๋ฐ ํŒŒ๋ž€์ƒ‰ ์ˆœ์„œ๋กœ ๋ฐฐ์—ด๋ฉ๋‹ˆ๋‹ค.

๋นจ๊ฐ„์ƒ‰, ํฐ์ƒ‰ ๋ฐ ํŒŒ๋ž€์ƒ‰์„ ๊ฐ๊ฐ ๋‚˜ํƒ€๋‚ด๊ธฐ ์œ„ํ•ด ์ •์ˆ˜ 0, 1 ๋ฐ 2๋ฅผ ์‚ฌ์šฉํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ ์ •๋ ฌ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

๋ฌธ์ œ ์›๋ฌธ: https://leetcode.com/problems/sort-colors/description/

 

 

๋ฌธ์ œ ํ’€์ด

 

  • ์ƒ‰์ƒ ๊ฐœ์ˆ˜๊ฐ€ ๋งŽ์ง€ ์•Š์œผ๋‹ˆ๊นŒ target ์ƒ‰์ƒ์„ ๋ฐ”๊ฟ”๊ฐ€๋ฉด์„œ sorting์„ ํ•˜์ž
  • in_place ๋กœ sorting์„ ํ•ด์•ผํ•˜๋‹ˆ๊นŒ, swapํ•ด์•ผํ•  index๋ฅผ ๊ธฐ์–ตํ•ด๊ฐ€๋ฉด์„œ swapํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์งœ์ž.
  • ํ˜„์žฌ ์ƒ‰์ƒ์œผ๋กœ swapํ•  ๊ณต๊ฐ„์„ ์ฐพ๊ณ , ๊ทธ๋‹ค์Œ swapํ•  index๋ฅผ ์ฐพ๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ ํ•ด๊ฒฐ

 

Runtime: 0ms Beats100.00%of users with C++
Memory: 9.88MB Beats32.94%of users with C++
 
 ๋ฉ”๋ชจ๋ฆฌ๋Š” color ๊ฐ’ ๋ฒกํ„ฐ๋•Œ๋ฌธ์ธ๋“ฏ, ๊ทธ๋ƒฅ 3 ์ดํ•˜์ผ๋•Œ๊นŒ์ง€๋กœ loop๋ฅผ ์ˆ˜์ •ํ•˜๋ฉด swap ์šฉ ๋ฉ”๋ชจ๋ฆฌ๋งŒ ์‚ฌ์šฉํ•˜๋‹ˆ๊นŒ ์ข€ ๋” ์ตœ์ ํ™” ๊ฐ€๋Šฅ.
class Solution {
public:
    void sortColors(vector<int>& nums) {

        vector<int> colors={0,1,2};
        int last_idx = 0;

        for(auto color: colors){
            for(int i = 0; i < nums.size(); ++i){
                if(nums[i] == color){
                    auto swp = nums[last_idx];
                    nums[last_idx++] = nums[i];
                    nums[i] = swp;
                }
                // update last_idx
                while(last_idx < nums.size() && nums[last_idx] < color){
                    last_idx++;
                }
            }
        }

    }
};

 

 

 

๋ฐ˜์‘ํ˜•

'IN DEPTH CAKE > Supercoder' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[c++/LeetCode-Stack] 155. MinStack  (1) 2024.05.05
[c++/LeetCode-2DArray] 48. Rotate Image  (1) 2024.05.05
[c++/LeetCode-Array] 56. Merge Intervals  (2) 2024.05.04
[c++/LeetCode-Array] 162. Find Peak Element  (1) 2024.05.02
[์ฝ”๋”ฉ/LeetCode150-(11)] 274. H-Index  (2) 2023.08.23
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.

# ๋กœ๋”ฉ ํ™”๋ฉด ๋™์ž‘ ์ฝ”๋“œ(Code) ์„ค์ •ํ•˜๊ธฐ