75. Sort Colors

Posted Carl_Hugo

tags:

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

https://leetcode.com/problems/sort-colors/description/

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的顺序)
设置首尾两个指针zero和second,zero左半边都为0,second右半边都为2。
如果遍历到的元素为0且在zero的右半边,则将当前元素与zero指针所指元素交换位置zero++;
如果遍历到的元素为2且在second的左半边,则将当前元素与second指针所指元素交换second–;

class Solution 
    public void sortColors(int[] nums) 
        int zero = 0;
        int second = nums.length-1;
        for(int i=0;i<=second;i++)
            while(nums[i]==2&&i<second)
                int temp = nums[i];
                nums[i]=nums[second];
                nums[second]=temp;
                second--;
            
            while(nums[i]==0&&i>zero)
                int temp = nums[i];
                nums[i] = nums[zero];
                nums[zero]=temp;
                zero++;
            
        
    

以上是关于75. Sort Colors的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 75. Sort Colors

75. Sort Colors

75. Sort Colors

75. Sort Colors

75. Sort Colors

75. Sort Colors