LeetCode-75. Sort Colors

来源:互联网 发布:油画淘宝详情页模版 编辑:程序博客网 时间:2024/06/06 03:00

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.

类似于快速排序的算法。

class Solution {public:    void sortColors(int A[], int n) {        int left=0;        int right=n-1;        int i=0;        while(i<=right){            if(A[i]==0){                swap(A[left],A[i]);                left++;                i++;            }            else if(A[i]==1){                i++;            }            else{                swap(A[right],A[i]);                right--;            }        }    }};

2017-12-1更新

官网上有个提示,是个很直接的方法,思路:

1、第一次遍历数组,将其中0.1.2的数量记录下来。

2、第二遍遍历数组,用记录下来0.1.2的数量给数组赋值。

Java实现

class Solution {    public void sortColors(int[] nums) {        int[] count = {0,0,0};        for(int i=0;i<nums.length;++i)        {            if(nums[i]==0)                count[0]++;            else if(nums[i]==1)                count[1]++;            else                count[2]++;        }        for(int i=0;i<count[0];++i)            nums[i]=0;        for(int i=0;i<count[1];++i)            nums[count[0]+i]=1;        for(int i=0;i<count[2];++i)            nums[count[0]+count[1]+i]=2;    }}


原创粉丝点击