75. Sort Colors

最后更新

四刷(我怎么觉得三刷没做完就四刷了。。)

典型的Partition,总结出一个general的方法了。

Time: O(n)

public class Solution {
    public void sortColors(int[] nums) {
        if (nums.length <= 1) return;
        
        int left = 0;
        int right = nums.length - 1;
        int temp = left;
        while (temp <= right) {
            if (nums[temp] == 1) {
                temp ++;
            } else if (nums[temp] == 0) {
                swap(temp ++, left ++, nums);
            } else {
                swap(temp, right --, nums);
            }
        }
        return;
    }
    
    public void swap(int l, int r, int[] nums) {
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
    }
}

一般follow up是sort k colors,比如 PocketGem的面试题。 (吐槽下这个傻逼公司的印度人,题都他妈做对了给我挂了。仔细一想我面试挂都是印度人挂的)

Sort K colors

K是最大值,假设最小是0。。

用0 1 2试验是过的= = 记得lintcode上有原题。

public class Solution {
    public void sortColors(int[] nums) {
        if (nums.length <= 1) return;
        int k = 2;
        int start = 0;
        int end = nums.length - 1;
        
        int min = 0;
        int max = k;
        
        while (start < end) {
            int temp = start;
            while (temp <= end) {
                if (nums[temp] == min) {
                    swap(temp ++, start ++, nums);
                } else if (nums[temp] == max) {
                    swap(temp, end --, nums);
                } else {
                    temp ++;
                }
            }
            min ++;
            max --;
        }
        return;
    }
    
    public void swap(int l, int r, int[] nums) {
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
    }
}

二刷。。

一样的做法。。

public class Solution {
    public void sortColors(int[] nums) {
        if (nums.length <= 1) return;
        int red = 0, blue = 0;
        for (int white = 0; white < nums.length - blue; white++) {
            if (nums[white] == 0) {
                nums[white] = nums[red];
                nums[red++] = 0;
            } else if (nums[white] == 1) {
            
            } else {
                nums[white] = nums[nums.length-1-blue];
                nums[nums.length-1-blue] = 2;
                blue++;
                white--;
            }
        }
        
        return;
    }
}

三刷。

记录3种颜色的数量,partition..

public class Solution {
    public void sortColors(int[] nums) {
        if (nums.length <= 1) return;
        // 0 red.   1 white,   2 blue
        int r = 0;
        int b = 0;
        for (int w = 0; w < nums.length - b; w++) {
            if (nums[w] == 0) {
                nums[w] = nums[r];
                nums[r++] = 0;
            } else if (nums[w] == 1) {
                continue;
            } else {
                nums[w] = nums[nums.length - b - 1];
                nums[nums.length - b - 1] = 2;
                b ++;
                w--;
            }
        }
        
        return;
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/6168422.html