[leetcode #75] Sort Colors

Seongyeol Shin·2021년 10월 27일
0

leetcode

목록 보기
62/196
post-thumbnail
post-custom-banner

Problem

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.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Idea

세 가지 색깔을 순서대로 정렬하라는 문제다.

주어진 array를 탐색하면서 빨강, 하양, 파랑 세 가지 색의 count를 센다. 세 가지 색의 count만큼 array의 값을 바꿔주면 정렬이 완료된다.

(이렇게 푸는게 맞나?)

Solution

class Solution {
    public void sortColors(int[] nums) {
        int red = 0;
        int white = 0;
        int blue = 0;
    
        for (int num : nums) {
            switch(num) {
                case 0:
                    red++;
                    break;
                case 1:
                    white++;
                    break;
                case 2:
                    blue++;
                    break;
            }
        }
    
        for (int i=0; i < red; i++) 
            nums[i] = 0;
    
        for (int i=red; i < red + white; i++)
            nums[i] = 1;

        for (int i=red+white; i < red + white + blue; i++)
            nums[i] = 2;
    }
}

Reference

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

profile
서버개발자 토모입니다
post-custom-banner

0개의 댓글