O(n) time, with constant space


  • 0
    R

    Please Note the index value only goes from 0 to nums.length-1, so it's one pass.

    public static void sortColors(int[] nums) {
            //O(n) complexity and with constant space
            
            int val=0,index=0;
            int temp;
            
            //determine the initial index
            while(nums[index]==0)
            {
                if(index<nums.length-1)
                    index++;
                else
                    break;
            }
            
            while(val<3)
            {
                for(int i=index+1;i<nums.length;i++)
                {
                    if(nums[i]!=val)
                        continue;
                    else
                    {
                        //swap
                        temp=nums[i];
                        nums[i]=nums[index];
                        nums[index]=temp;
                        index++;
                    }
                }
                val++;
                while(nums[index]==val)
                {
                if(index<nums.length-1)
                    index++;
                else
                    break;
                }
            }
        }
    

Log in to reply
 

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