A simple python solution with O(n) complexity


  • 0
    K
    class Solution:
        # @param {integer[]} nums
        # @return {void} Do not return anything, modify nums in-place instead.
        def sortColors(self, nums):
            i = k = 0
            j = len(nums) - 1
            while k <= j:
                if nums[k] == 0:
                    nums[i], nums[k] = nums[k], nums[i]
                    i += 1
                if nums[k] == 2:
                    nums[j], nums[k] = nums[k], nums[j]
                    j -= 1
                    k -= 1
                k += 1

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.