Sort Colors Solutions in Python
Number 75
Difficulty Medium
Acceptance 47.4%
Link LeetCode
Solutions
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/sort-colors/# Author : penpenps# Time : 2019-05-31from typing import List# Counting and reset nums in order# Time Complexity: O(2*n)# Space Complexity: O(3)class Solution:def sortColors(self, nums: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""m = [0]*3for x in nums:m[x] += 1for i in range(len(nums)):if i < m[0]:nums[i] = 0if m[0] <= i < m[1] + m[0]:nums[i] = 1if i >= m[0] + m[1]:nums[i] = 2if __name__ == '__main__':s = Solution()nums = [2,0,2,1,1,0]s.sortColors(nums)print(nums)
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/sort-colors/# Author : penpenps# Time : 2019-05-31from typing import List# Quick sort for 3 numbers# Time Complexity: O(n)# Space Complexity: O(3)class Solution:def sortColors(self, nums: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""zero = 0two = len(nums) - 1i = 0while i <= two:if nums[i] == 0:nums[i], nums[zero] = nums[zero], nums[i]zero += 1i += 1elif nums[i] == 2:nums[i], nums[two] = nums[two], nums[i]two -= 1else:i += 1if __name__ == '__main__':s = Solution()nums = [2,0,2,1,1,0]s.sortColors(nums)print(nums)
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/sort-colors/# Author : penpenps# Time : 2019-05-31from typing import List# use [i, j) to keep 0, [j, k) keeps 1 and [k, ] keeps 2# Time Complexity: O(n)# Space Complexity: O(4)class Solution:def sortColors(self, nums: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""i, j, k = 0, 0, 0for k in range(len(nums)):v = nums[k]nums[k] = 2if v < 2:nums[j] = 1j += 1if v < 1:nums[i] = 0i += 1if __name__ == '__main__':s = Solution()nums = [2,0,2,1,1,0]s.sortColors(nums)print(nums)