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; } }}
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 【leetcode】75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- Leetcode 75. Sort Colors
- [LeetCode]75. Sort Colors
- LeetCode 75. Sort Colors
- LeetCode *** 75. Sort Colors
- leetcode 75. Sort Colors
- LeetCode 75. Sort Colors
- leetcode-75. Sort Colors
- [leetcode]75. Sort Colors
- LeetCode-75.Sort Colors
- 日常问题总结(10)
- 图像基础14 图像滤波与除噪——均一化块滤波(高斯、椒盐)
- 发布一个月,iOS 11 安装普及率达到 55%
- PS CS6 forMac 中文破解版下载及破解方法
- 从零开始学习TFLearn(二)
- leetcode 75. Sort Colors
- DXP AD 绘制一个扁长型的过孔
- Android 全选 全不选 反选 获得选中的下标
- linux早期经典字符设备驱动模型
- EL表达式中等于、不等于、小于、大于
- [二分图匹配] HHHOJ#51. Book
- MyEclipse2017版本去除自带tomcat的方法
- 用友、金山……3份行业深度洞察报告,100+主流厂商,300+业内大咖,企服三会与你洞见2018 | 【企服三会·2018】
- ——致远互联渠道伙伴系列访谈之四川凤凰世纪