Java Simple solution, easy to understand. O(N) Time Complexity.


  • 1
    M

    My Solution:

        private static void sortColors(int[] arr) {
    
    	int[] counts = new int[3];
    
    	for(int i: arr)
    		counts[i]++;
    	
    	for(int i = 0; i < arr.length; i++) {
    		if(i < counts[0])
    			arr[i] = 0;
    		else if (i >= counts[0] && i < counts[0] + counts[1])
    			arr[i] = 1;
    		else
    			arr[i] = 2;
    	}
    }

Log in to reply
 

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