LeetCode-Sort Colors

来源:互联网 发布:北京纸箱厂 淘宝定做 编辑:程序博客网 时间:2024/04/27 22:36

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.

brute force的方法就是一遍把三种颜色都数一遍, 然后再一遍一个一个赋值。走一遍的方法就是两个指针,一个在前面指排好的0的末尾,另一个在后面指排好的2的最前面,只要是遇到0 2 就swap,1就不用管。注意要用while,就是可能换过来的那个数字也要继续swap。同时两个while的先后顺序是有关系的,要先处理好2的情况,再swap所有0的情况。因为有可能从后面swap 2的时候,换过来一个0,但是不可能swap 0的时候从前面换过来一个2.因为current指的位置之前只可能有0和1.

public class Solution {    public void sortColors(int[] A) {        if (A ==null || A.length == 0)            return;        int first = 0;        int last = A.length -1;        for ( int i = 0; i <= last; i ++){                while ( A[i] == 2 && i < last){                    int temp = A[i];                    A[i] = A[last];                    A[last] = temp;                    last --;                }                while ( A[i] == 0 && i > first){                    int temp = A[i];                    A[i] = A[first];                    A[first] = temp;                    first ++;                }        }    }}
还有一个解法没仔细研究 感觉不太好想。

void sortColors(int A[], int n) {    int n0 = -1, n1 = -1, n2 = -1;    for (int i = 0; i < n; ++i) {        if (A[i] == 0)         {            A[++n2] = 2; A[++n1] = 1; A[++n0] = 0;        }        else if (A[i] == 1)         {            A[++n2] = 2; A[++n1] = 1;        }        else if (A[i] == 2)         {            A[++n2] = 2;        }    }}




0 0