본문 바로가기
LeetCode

75. Sort Colors LeetCode C++

by O_x 2022. 6. 20.

https://leetcode.com/problems/sort-colors/description/

 

Sort Colors - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

빨간색, 흰색 또는 파란색으로 색칠된 n개의 객체가 있는 배열 번호가 
주어지면 동일한 색상의 객체가 인접하도록 제자리에서 정렬하고 색상은 빨간색, 흰색, 파란색으로 지정합니다.

정수 0, 1, 2를 사용하여 빨강, 흰색, 파랑을 각각 나타냅니다.

라이브러리의 정렬 기능을 사용하지 않고 이 문제를 해결해야 합니다.

 

 

 

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]

 

Constraints:

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

 문제 조건에 보면   in-place를 통해 구현하라고 되어 있다. 그렇기에 이문제가 중간정도의 난이도를 가진다.

in-place 가 아니였다면 0의 갯수 1의 갯수 2의 갯수를 구하여 0부터 출력했으면 됬을 것이다.

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int idx0 = 0;
        int idx2 = nums.size()-1;
        int i = 0;
        
        while(i <= idx2)
        {
            if(nums[i] == 0){
                swap(nums[i], nums[idx0]);
                idx0++;
                i++;
            }
            else if(nums[i]==2){
                swap(nums[i],nums[idx2]);
                idx2--;
            }
            else i++;
        }
    }
};

 

else if(nums[i]==2) 부분에서 idx0를 ++하지 않는 이유는 idx2의 값이 1일 수도 0일 수도 있기 때문이다.

'LeetCode' 카테고리의 다른 글

162. Find Peak Element c++ 문제  (0) 2022.06.21
88. Merge Sorted Array c++ 문제  (0) 2022.06.20
Leetcode 704번 Find Pivot Index 해설  (0) 2022.06.19
LeetCode 283번 Move Zeroes  (0) 2022.06.11
Binary search LeetCode-704 문제  (0) 2022.06.11

댓글