75. Sort Colors

2016-11-11  本文已影响4人  exialym

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;
        }
    }
};
上一篇 下一篇

猜你喜欢

热点阅读