My Java accepted answer using insertion sort


  • 0
    J
    public class Solution {
        public void sortColors(int[] nums) {
    	if(nums==null||nums.length==0)
    		return ;
        int j;    
    	for (int i = 1; i < nums.length; i++) {
    			j=i;
    			int temp = nums[i];
    			while(j>0&&nums[j-1]>temp){
    				nums[j]=nums[j-1];
    				j--;
    			}
    			nums[j]= temp;
    		}
        }
    }

  • 0
    B

    The problem has already limited that all numbers will be between 0 and 2 and that you just need to sort them.

    In fact there is no need to apply any O(nlgn) or O(n^2) algorithm. You can sort the numbers manually by Counting Sort.


Log in to reply
 

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