LeetCode-75~Sort Colors

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.
给定一个数组,由n个分别涂有红、白、蓝颜色的对象组成,给数组排序,使得有相同颜色的对象相邻,其中,颜色顺序为红、白、蓝。
使用0、1、2分别表示红、白、蓝
注意:不建议使用库中排序函数解决问题

算法分析

利用三个索引标志,begin、end分别表示白色的首尾位置。

Java代码

public class Solution {
    public void sortColors(int[] nums) {
        int begin = 0, end = nums.length - 1, curr = 0;//begin和end分别表示颜色为1的开始和结尾索引
        while(curr <= end) {//有等号是因为我们至判断nums[curr],并未判断nums[end],因此最后一步就需要判断nums[end]
            if (nums[curr] == 0) {
                if (curr != begin) {
                    int temp = nums[curr];
                    nums[curr] = nums[begin];
                    nums[begin] = temp;
                }
                curr ++;
                begin ++;
            } else if (nums[curr] == 1) {
                curr ++;
            } else if (nums[curr] == 2) {
                if (curr != end) {
                    int temp = nums[curr];
                    nums[curr] = nums[end];
                    nums[end] = temp;
                }
                end --;
                //curr ++;此处curr不能加yi的原因是,与end索引处置换后的值还未判断,需要再进行判断一次
            }
        }
    }
}

参考

oschina
LeetCode

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容