코딩 테스트 (Python)/리트코드

[리트코드] 75. 색 정렬 (Python)

hihyuk 2024. 1. 17. 15:25
 

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

문제

빨간색, 흰색 또는 파란색으로 색상이 지정된 개체 가 있는 배열 nums이 주어지면 동일한 색상의 개체가 빨간색, 흰색 및 파란색 순서로 색상이 인접하도록 정렬하는 프로그램을 작성하시오

과정

  • 정렬을 이용하여 풀어준다.

 

입력

[2,0,2,1,1,0]

출력

[0,0,1,1,2,2]

 

풀이

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        for i in range(len(nums)):
            for j in range(len(nums)-1-i):
                if nums[j] > nums[j+1]:
                    nums[j], nums[j+1] = nums[j+1], nums[j]

 

한 줄 씩 해석해보기

for i in range(len(nums)):
    for j in range(len(nums)-1-i):
        if nums[j] > nums[j+1]:
            nums[j], nums[j+1] = nums[j+1], nums[j]
  • 버블정렬
  • 문자열의 길이만큼 탐색한다
  • 문자열의 길이에서 현재 위치와 1을 뺀값까지 탐색하며 비교한다.
  • 만약 현재 값이 그 다음값보다 크다면
  • 서로의 위치를 바꾸어준다.

 

간단한 풀이

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        nums.sort()
  • sort()를 이용한 풀이