leetcode 75. Sort Colors

来源:互联网 发布:浅析网络直播 编辑:程序博客网 时间:2024/06/03 20:45

生命不息,奋斗不止


@author stormma
@date 2017/10/19


题目
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的数组然后你排序成0区,1区,2区的这种形式,这就是著名的荷兰国旗问题。

思路分析
设三个指针,初始化pos0(0区指针) = 0, pos2(2区指针) = length-1 , currentPos(当前位置指针) = 0,然后从currentPos开始判断,如果是0就和pos0这个位置的数据交换,然后pos0++, currentPos++,如果是2,那么和pos2位置交换,pos2--此时currentPos不增加(因为交换过来的上一个pos2位置的数据还没进行判断), 如果是1, currentPos++就行了,循环直到currentPos > pos2为止。

代码实现

/** * <p>荷兰国旗问题,<a href="https://leetcode.com/problems/sort-colors">题目链接</a></p> * * @author stormma * @date 2017/10/19 */public class Question75 {    static class Solution {        public void sortColors(int[] nums) {            int pos0 = 0, pos2 = nums.length - 1, currentPos =0;            while (currentPos <= pos2) {                if (nums[currentPos] == 0) {                    swap(nums, currentPos, pos0);                    pos0++;                    currentPos++;                    continue;                }                if (nums[currentPos] == 2) {                    swap(nums, currentPos, pos2);                    pos2--;                    continue;                }                currentPos++;            }            show(nums);        }        private static void show(int[] array) {            for (int anArray : array) {                System.out.print(anArray + " ");            }            System.out.println();        }        private static void swap(int[] nums, int a, int b) {            int temp = nums[a];            nums[a] = nums[b];            nums[b] = temp;        }    }}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果手机激活锁忘了id账号怎么办 淘宝很多产品都需要3c怎么办 小米mix装在兜里还能解锁怎么办 痰咳不出来憋的嘴唇紫了怎么办 京东闪电退款后不给退货怎么办 我的中国银行卡在异地被冻结怎么办 qq密保号码换了验证不了怎么办 qq登陆需要密保手机验证怎么办 微信漂流瓶被投诉收不到回复怎么办 电视的屏幕出现三条黑线怎么办 付了定金的房子不想要了怎么办 顾客刚买了东西就退怎么办 飞机票买了但是没有报团怎么办 日本寄东西回来深圳海关扣了怎么办 xp框架安装模块后无限重启怎么办 手机百度云下载的文件不见了怎么办 百度云手机号换了文件不见了怎么办 好劵app提现密码忘了要怎么办 微信上买的衣服不给退货怎么办 在微信上买的衣服不给退货怎么办 贴贴纸的地方出现色差了怎么办 贴在玻璃上的贴纸撕掉后有胶怎么办 魅族手机部分时间上划失效怎么办 别人电脑上c盘文件无权访问怎么办 网络已连接但上不了网怎么办 asp复选框选中的有重复值怎么办 邮件在邮递中出现损坏怎么办呢? 爱彩彩票资金密码忘记了怎么办 注册彩票网站忘了资金密码怎么办 电车电瓶加水后电压变低怎么办 电动车电瓶四块电池坏了一块怎么办 把小孩的玩具修坏了怎么办 电动车插头太紧了插不到底怎么办 宜家沙发不能更换布套怎么办 苹果官网买的无线充坏了怎么办 苹果官网上买的耳机坏了怎么办 led灯开关关掉了闪烁是怎么办 我朋友借的网贷光给我打电话怎么办 电脑上的文件变成了图片查看怎么办 外卖店打印机纸卡住打不开了怎么办 微信撤回图片留下一堆代码怎么办