美文网首页
75. Sort Colors

75. Sort Colors

作者: exialym | 来源:发表于2016-11-11 10:49 被阅读4次

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
说白了就是把包含乱序0,1,2的数组排序
你可以直接用任何排序算法来做这道题,但是因为只有0,1,2,你可以做一些优化。
第一种办法是走两遍,第一遍记下0,1,2的数目,第二遍改写数组。
第二种是走一遍,把0,2移到数组的两端

var sortColors = function(nums) {
    var num = nums.length;
    if (num<=1)
        return;
    var left = 0;
    var right = num - 1;
    for (var i = 0;i < num;i++) {
        while (nums[i]===2&&i<right) {
            nums[i] = nums[right];
            nums[right--] = 2;
        }
         while (nums[i]===0&&i>left) {
            nums[i] = nums[left];
            nums[left++] = 0;
        }
    }
};

相关文章

网友评论

      本文标题:75. Sort Colors

      本文链接:https://www.haomeiwen.com/subject/lxcfpttx.html