LeetCode: Sort Colors Solution

Count and overwrite

Approach

Counting occurences of

0, 1, 2

Overwrite the original array with the occurences

Implementation

1var sortColors = function (nums) {
2 const colorCount = nums.reduce((arr, num) => {
3 arr[num]++
4 return arr
5 }, new Int8Array(3))
6
7 for (let i = (j = 0); i < nums.length; i++) {
8 while (colorCount[j] === 0) j++
9
10 nums[i] = j
11
12 colorCount[j]--
13 }
14}

References

Original problem

Similar problems

Sort List

Wiggle Sort

Wiggle Sort II

Comments

Loading comments...

Tags

leetcode

sorting

Next Post

LeetCode: Same Tree

Sep 28, 2022

Recursion

Previous Post

LeetCode: Split Linked List in Parts

Sep 24, 2022

Naming is hard

HoningJS

Search Posts