Swift solution - Two Pointers


  • 0
    class Solution {
        func sortColors_TwoPointers(_ nums: inout [Int]) {
            if nums.count == 0 {
                return
            }
            
            var left = 0
            var right = nums.count - 1
            
            for i in 0...right {
                while nums[i] == 2 && i < right {
                    swap(&nums[i], &nums[right])
                    right -= 1
                }
                while nums[i] == 0 && i > left {
                    swap(&nums[i], &nums[left])
                    left += 1
                }
            }
        }
        
        func sortColors(_ nums: inout [Int]) {
            if nums.count == 0 {
                return
            }
            
            var r = 0
            var w = 0
            var b = 0
            
            for num in nums {
                if num == 0 {
                    nums[b] = 2
                    b += 1
                    nums[w] = 1
                    w += 1
                    nums[r] = 0
                    r += 1
                } else if num == 1 {
                    nums[b] = 2
                    b += 1
                    nums[w] = 1
                    w += 1
                } else if num == 2 {
                    b += 1
                }
            }
        }
    }
    

Log in to reply
 

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