Straightforward Java 2ms Solution


  • 0
    A
    public void sortColors(int[] nums) {
            if(nums.length == 1) return;
            Map<Integer, Integer> colorMap = new HashMap<Integer, Integer>();
            for(int num: nums){
                if(!colorMap.containsKey(num)){
                    colorMap.put(num, 0);
                }
                colorMap.put(num, colorMap.get(num) + 1);
            }
            int [] res = new int[nums.length];
            int numRed = 0, numWhite = 0, numBlue = 0;
            if(colorMap.containsKey(0)){
                numRed = colorMap.get(0);
                for(int i = 0; i < numRed; i++){
                    res[i] = 0;
                }
            }
            if(colorMap.containsKey(1)){
                numWhite = colorMap.get(1);
                for(int j = numRed; j < (numWhite + numRed); j++){
                    res[j] = 1;
                }
            }
            if(colorMap.containsKey(2)){
                numBlue = colorMap.get(2);
                for(int k = (numWhite+numRed); k < (numBlue+numWhite+numRed); k++){
                    res[k] = 2;
                }
            }
            for(int i = 0; i < nums.length; i++){
                nums[i] = res[i];
            }
        }
    

Log in to reply
 

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