Alternate approach to solve the problem using element counting


  • 0
    M
     public class Solution {
        public void sortColors(int[] nums) {
            if(nums == null || nums.length<=1) return;
            
            int[] colors = new int[3];
            
            for(int i = 0; i<nums.length; i++) {
                colors[nums[i]]++;
            }
            int index = 0;
            for(int i = 0; i<colors.length; i++) {
                for(int j = 0; j<colors[i]; j++) {
                    nums[index++] = i;
                }
            }
        }
    }
    

Log in to reply
 

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