143. Sort Colors II

最后更新

一刷

class Solution {
    public void sortColors2(int[] colors, int k) {
        // write your code here
        if (colors.length <= 1) return;
        int start = 0;
        int end = colors.length - 1;
        int min = 1;
        int max = k;
        
        while (start < end) {
            int temp = start;
            while (temp <= end) {
                if (colors[temp] == min) {
                    swap(start ++, temp ++, colors);
                } else if (colors[temp] == max) {
                    swap(end --, temp, colors);
                } else {
                    temp ++;
                }
            }
            min ++;
            max --;
        }
    }
    
    public void swap(int l, int r, int[] colors) {
        int temp = colors[l];
        colors[l] = colors[r];
        colors[r] = temp;
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/6219289.html