LeetCode: Sort Colors Solution
Count and overwriteApproach
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 arr5 }, new Int8Array(3))67 for (let i = (j = 0); i < nums.length; i++) {8 while (colorCount[j] === 0) j++910 nums[i] = j1112 colorCount[j]--13 }14}
References
Similar problems
Wiggle Sort
Wiggle Sort II
Comments
Loading comments...
Tags
leetcode
sorting
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.