75. Sort Colors

题目:

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.

Note:
You are not suppose to use the library's sort function for this problem.

链接: http://leetcode.com/problems/sort-colors/

题解: 排序0, 1和2,把0交换到数组头,2交换到数组末尾,1不变。这题在Microsoft的电面里被问到过。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public void sortColors(int[] A) {

        if(A == null || A.length == 0)

            return;

        int index = 0, left = 0 , right = A.length - 1;

        

        while(index <= right){

            if(A[index] == 0){

                swap(A, index ++, left ++);

            } else if (A[index] == 1)

                index ++;

            else

                swap(A, index, right --);

        }

        

    }

    

    private void swap(int[] A, int m , int n){

        int temp = A[m];

        A[m] = A[n];

        A[n] = temp;

    }

}

 

测试:

你可能感兴趣的:(color)