My counting sort solution in java


  • 0
    M

    This is my counting sort solution to sort color

    public class Solution {
    public void sortColors(int[] nums) {
        int[] cnt = new int[3];
        cnt[0] = 0;
        cnt[1] = 0;
        cnt[2] = 0;
        for (int i : nums)
            cnt[i] += 1;
        int index = 0;
        for (int i = 0; i < cnt.length; i += 1){
            while (cnt[i] > 0 && index < nums.length){
                nums[index] = i;
                cnt[i] -= 1;
                index += 1;
            }
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.