[leetcode]75.Sort Color三指针

Posted stAr_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]75.Sort Color三指针相关的知识,希望对你有一定的参考价值。

import java.util.Arrays;

/**
 * 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.

 click to show follow up.

 Follow up:
 A rather straight forward solution is a two-pass algorithm using counting sort.
 First, iterate the array counting number of 0‘s, 1‘s, and 2‘s,
 then overwrite array with total number of 0‘s, then 1‘s and followed by 2‘s.

 Could you come up with an one-pass algorithm using only constant space?
 */
/*
* 两种解法
* 1.三个指针:红指针,蓝指针,遍历指针(循环指针i),红蓝指针比别从前后端记录红色区域和蓝色区域的边界位置,
* 遍历指针负责找到红蓝颜色的数据,白色的不用管,最后中间剩下的就是白色
* 2.记录红白蓝三色出现的次数,最后直接对数组进行相应的赋值
* 这里选用第一种
* 容易出错的地方:遍历指针和边界指针交换之后,还要在遍历指针的位置再判断一下是不是其他颜色,
* 所以比较适合写成两个if分别判断,而且后边的if要加i--*/
public class Q75SortColors {
    public static void main(String[] args) {
        int[] nums = new int[]{2,2,2};
        sortColors(nums);
        System.out.println(Arrays.toString(nums));
    }
    public static void sortColors(int[] nums) {
        int red = 0;
        int blue = nums.length - 1;
        int temp;
        //获取红色区域的初始边界
        for (int i =0;i < nums.length;i++)
        {
            if (nums[i] != 0)
            {
                red = i;
                break;
            }
            
        }
        //获取蓝色区域的初始边界
        for (int i =nums.length-1;i >= 0 ;i--)
        {
            if (nums[i] != 2)
            {
                blue = i;
                break;
            }

        }
        //遍历交换归位
        for (int i =red;i <= blue ;i++)
        {
            if (nums[i] == 0)
            {
                temp = nums[red];
                nums[red] = nums[i];
                nums[i] = temp;
                red++;
            }
            if (nums[i] == 2)
            {
                temp = nums[blue];
                nums[blue] = nums[i];
                nums[i] = temp;
                blue--;
                i--;
            }
        }
    }
}

 

以上是关于[leetcode]75.Sort Color三指针的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 75. Sort Colors

[leetcode-75-Sort Colors]

Leetcode 75. Sort Colors

LeetCode 75 Sort Colors

LeetCode 75 Sort Colors

leetcode75 Sort Colors