Want a code that works for arbitrarily any color?


  • 0
    P

    Actually we can have a code that works for arbitrarily many colors, as long as the colors are numbered with consecutive integers starting at 0. The number of colors does not even has to be part of the input. Try it out! Have fun.

    public class Solution {
        public void sortColors(int[] nums) {
            int color = 0;
            int i = 0;
            while(i < nums.length) {
                if(nums[i] != color) {
                    int j = i + 1;
                    while(j < nums.length && nums[j] != color) {
                        j++;
                    }
                    if(j < nums.length) {
                        nums[j] = nums[i];
                        nums[i] = color;
                        i++;
                    }else {
                        color++;
                    }
                }else {
                    i++;
                }
            }
        }
    }
    

  • 0

    Hi @pprabbit this idea great.
    But it seems the time complexity is O(n^2), you can use this as a test case:
    5, 4, 3, 2, 1


Log in to reply
 

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