LeetCode – Sort Colors (Java)
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Java Solution - Counting Sort
We can get the count of each element and project them to the original array.
public void sortColors(int[] nums) { if(nums==null||nums.length<2){ return; } int[] countArray = new int[3]; for(int i=0; i<nums.length; i++){ countArray[nums[i]]++; } int j = 0; int k = 0; while(j<=2){ if(countArray[j]!=0){ nums[k++]=j; countArray[j] = countArray[j]-1; }else{ j++; } } } |
<pre><code> String foo = "bar"; </code></pre>
-
Vasyl Grygoryev
-
up23