75. 颜色分类

题目:

思路:

【1】利用统计的方式

【2】单指针的方式

【3】双指针的方式(该方式其实算是对单指针的合并)

代码展示:

【1】利用统计的方式

//时间0 ms 击败 100%
//内存40.2 MB 击败 12.27%
class Solution {
    public void sortColors(int[] nums) {
        int count0 = 0 , count2 = 0;
        for (int i = 0; i < nums.length;i++){
            if (nums[i] == 0) count0++;
            if (nums[i] == 2) count2++;
            nums[i] = 1;
        }
        while (count0-- > 0) nums[count0] = 0;
        while (count2-- > 0) nums[nums.length - 1 - count2] = 2;
    }
}

【2】单指针的方式

//时间0 ms 击败 100%
//内存39.9 MB 击败 76.30%
class Solution {
    public void sortColors(int[] nums) {
        int n = nums.length;
        int ptr = 0;
        for (int i = 0; i < n; ++i) {
            if (nums[i] == 0) {
                int temp = nums[i];
                nums[i] = nums[ptr];
                nums[ptr] = temp;
                ++ptr;
            }
        }
        for (int i = ptr; i < n; ++i) {
            if (nums[i] == 1) {
                int temp = nums[i];
                nums[i] = nums[ptr];
                nums[ptr] = temp;
                ++ptr;
            }
        }
    }
}

 

【3】双指针的方式(该方式其实算是对单指针的合并)

//时间0 ms 击败 100%
//内存40.1 MB 击败 35.16%
class Solution {
    public void sortColors(int[] nums) {
        int n = nums.length;
        int p0 = 0, p1 = 0;
        for (int i = 0; i < n; ++i) {
            if (nums[i] == 1) {
                int temp = nums[i];
                nums[i] = nums[p1];
                nums[p1] = temp;
                ++p1;
            } else if (nums[i] == 0) {
                int temp = nums[i];
                nums[i] = nums[p0];
                nums[p0] = temp;
                if (p0 < p1) {
                    temp = nums[i];
                    nums[i] = nums[p1];
                    nums[p1] = temp;
                }
                ++p0;
                ++p1;
            }
        }
    }
}

 

posted @ 2023-08-03 11:58  忧愁的chafry  阅读(7)  评论(0编辑  收藏  举报