LeetCode Problem: Sort Colours
Problem statement:
Given an array (nums) with n objects colored 0, 1, or 2, sort them in-place so that objects of the same color are adjacent, with the colors in the order 0, 1, and 2.
Example:
Input:
[2,0,2,1,1,0]
Expected output:
[0,0,1,1,2,2]
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/sort-colors/
Golang Solution:
func sortColors(nums []int) {
if len(nums) <= 1 {
return
}
i, j := 0, 0
k := len(nums) - 1
for j <= k {
if nums[j] == 0 {
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1
} else if nums[j] == 2 {
nums[k], nums[j] = nums[j], nums[k]
k -= 1
} else {
j += 1
}
}
}