바위타는 두루미

[leetcode]75. Sort Colors 본문

Study/Algorithm

[leetcode]75. Sort Colors

DoRoMii 2019. 8. 10. 12:35
728x90

75. Sort Colors

 

Given an array 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.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
  • Could you come up with a one-pass algorithm using only constant space?

첫번째 solution:

two-pass algorithm using counting sort.

class Solution(object):
    def sortColors(self, nums):
        count = [0]*3
        for n in nums:
            count[n] += 1
        index = 0
        for i in range(len(nums)):
            while count[index] == 0:
                index +=1
            nums[i] = index
            count[index]-=1
        
        

두번째 solution:

one-pass algorithm using only constant space

class Solution(object):
    def sortColors(self, nums):
        red_point = 0
        blue_point = len(nums)-1
        
        
        for i in range(len(nums)):
            while nums[i] != 1 :
                if nums[i] == 0:
                    if i == red_point :
                        red_point +=1
                        break
                    else :
                        nums[red_point], nums[i] = nums[i], nums[red_point]
                        red_point +=1
                elif nums[i]==2:
                    if i> blue_point :
                        return
                    nums[blue_point], nums[i] = nums[i], nums[blue_point]
                    blue_point -=1

세번째 solution:

두번째 솔루션을 더 간단하게!

def sortColors(self, nums):			 
        l=len(nums)
        left=0
        right=l-1
        i=0
        while i<=right:
            if nums[i]==0:
                nums[i],nums[left]=nums[left],nums[i]
                left+=1
            elif nums[i]==2:
                nums[i],nums[right]=nums[right],nums[i]
                right-=1
                i-=1
            i+=1

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

'Study > Algorithm' 카테고리의 다른 글

[leetcode]347. Top K Frequent Elements  (0) 2019.08.10
[leetcode]347. Top K Frequent Elements  (0) 2019.08.10
[leetcode]79. Word Search  (0) 2019.08.10
[leetcode]78. Subsets  (0) 2019.08.10
[leetcode]46. Permutations  (0) 2019.08.10
Comments