코딩테스트

75. Sort Colors

nayoon 2024. 2. 18. 20:02

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

 

0ms

class Solution {
    public void sortColors(int[] nums) {
        int[] count = new int[3];
        for(int num: nums) {
            count[num]++;
        }
        int index = 0;

        for(int i = 0; i < nums.length; i++) {
            if (count[index] == 0) {
                index++;
                i--;
                continue;
            }
            nums[i] = index;
            count[index]--;
        }
    }
}

 

 

0ms

class Solution {
    public void sortColors(int[] nums) {
        int l = 0;
        int m = 0;
        int h = nums.length - 1;

        while(m <= h) {
            if (nums[m] == 0) {
                swap(nums, l, m);
                l++;
                m++;
            } else if (nums[m] == 1) {
                m++;
            }
            else if (nums[m] == 2) {
                swap(nums, m, h);
                h--;
            }
        }
    }
    public void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}

 

 

'코딩테스트' 카테고리의 다른 글

33. Search in Rotated Sorted Array  (0) 2024.02.22
994. Rotting Oranges  (0) 2024.02.21
268. Missing Number  (0) 2024.02.17
283. Move Zeroes  (0) 2024.02.17
100. Same Tree  (0) 2024.02.17