미소를뿌리는감자의 코딩

[leetcode 2024/02/22] 75. Sort Colors 본문

코딩 테스트/leetcode

[leetcode 2024/02/22] 75. Sort Colors

미뿌감 2024. 2. 22. 15:01
728x90

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

 

Sort Colors - LeetCode

Can you solve this real interview question? Sort Colors - Given an array nums with n objects colored red, white, or blue, sort them in-place [https://en.wikipedia.org/wiki/In-place_algorithm] so that objects of the same color are adjacent, with the colors

leetcode.com

 

1. 접근 방법

sort()로 풀면 쉽게 풀릴 문제이지만, 친히 ' You must solve this problem without using the library's sort function' 이라고 말씀해 주셨기에, insertion sort [ 삽입 정렬 ] 을 이용해서 풀어볼 것이다.

insertion sort를 이용한 이유는 추가적인 메모리 사용이 거의 없고, nums라는 list에 직접 결과를 반영할 수 있기 때문이다.

 

마침 어제, insertion sort에 대해서 적어둔 것이 있었다.

https://potatoscatteringsmile.tistory.com/138

 

python의 sort()의 시간 복잡도

python의 sort는 어떤 알고리즘을 사용할까? 주로 사용되는 정렬함수 [ sorted() ] 와 리스트 타입의 메소드 [ sort() ] 는 모두 내부적으로 'Timsort' 알고리즘을 사용한다. Timsort는 팀 피터스가 파이썬을

potatoscatteringsmile.tistory.com

 

코드를 작성할 때, 2번 Index 부터 비교하기 시작한 후, 정렬된 부분과 정렬되지 않은 부분으로 나누었다.

이후, 2번 index 부터 시작해서 정렬된 부분의 올바른 위치에 넣어주었다. 

정석적인 insertion sort에 대한 코드는 아래에서 확인하길 바란다.

https://www.geeksforgeeks.org/python-program-for-insertion-sort/

 

Python Program for Insertion Sort - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

2. 코드

class Solution:
    def sortColors(self, nums: List[int]) -> None:

        """
        Do not return anything, modify nums in-place instead.
        """

        for i in range(1, len(nums), 1):
            inserted = False
            compare_n = nums.pop(i)
            for sorted_n in range(0, i, 1):
                if nums[sorted_n] >= compare_n:
                    nums.insert(sorted_n, compare_n)
                    inserted = True
                    break
            if not inserted:
                nums.insert(i, compare_n)

        #print(nums)
728x90