JavaScript One Pass with Explaination


  • 4

    0_1474676686328_75. Sort Colors.jpg

    /**
     * @param {number[]} nums
     * @return {void} Do not return anything, modify nums in-place instead.
     */
    var sortColors = function(nums) {
        var low = 0,
            high = nums.length - 1,
            temp;
        
        for (var i = 0; i <= high; ) {
            if (nums[i] === 0) {
                temp = nums[i];
                nums[i] = nums[low];
                nums[low] = temp;
                i++;
                low++;
            } else if (nums[i] == 2) {
                temp = nums[i];
                nums[i] = nums[high];
                nums[high] = temp;
                high--;
            } else {
                i++;
            }
        }
    };
    

  • 0
    L
    This post is deleted!

Log in to reply
 

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