Sort Colors

来源:互联网 发布:剑网三炮哥捏脸数据 编辑:程序博客网 时间:2024/06/07 13:45

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.
题目的意思实际上就是给定一个数组,数组的里面的字符只有0,1,2三个数字,给数组排序但是不允许使用库函数
思路:先指定两个索引,分别指向数组的前后两端,从左边找一个不为0的数字和在右边找出第一个为0的数字,然后交换这两个数字,直到交换完,此时数组的分为两部分,前面的数字为0,后面的部分数字非0,然后排后面一半的数字,以同样的方法来交换1和2,直到交换完所有的1和2,此时数组排序就排好了。

代码如下:

public class Solution {    public void sortColors(int[] A) {        int length = A.length;        int i = 0;        int j = length - 1;        while (i < j ) {            while (i<length && A[i] == 0)                i++;            while (j>=0 && A[j] != 0)                j--;            if (i < j) {                int temp = A[i];                A[i] = A[j];                A[j] = temp;            }        }        int k = j + 1;        int s = length - 1;        while (k < s) {            while (k<length&&A[k] == 1)                k++;            while (s>=0 && A[s] != 1)                s--;            if (k < s) {                int temp = A[k];                A[k] = A[s];                A[s] = temp;            }        }    }}
0 0
原创粉丝点击