Intermediate Level
Implement the sortColorsThreeValues method that sorts an array containing only three possible values.
The input contains an integer array nums and its length size. The array contains only three possible values: 0, 1, and 2. Your task is to sort these values in ascending order.
For example, [2,0,2,1,1,0] should become [0,0,1,1,2,2].
Since there are only three possible values, count how many times each value appears.
After counting 0s, 1s, and 2s, overwrite the array by writing all 0s first, then all 1s, and finally all 2s.
Pseudocode:
function sortColorsThreeValues(nums, size):
count0 = 0
count1 = 0
count2 = 0
for each value in nums:
if value == 0:
count0++
else if value == 1:
count1++
else:
count2++
index = 0
repeat count0 times:
nums[index] = 0
index++
repeat count1 times:
nums[index] = 1
index++
repeat count2 times:
nums[index] = 2
index++
return nums