leetcode 75. Sort Colors
2017-10-20 08:48
375 查看
生命不息,奋斗不止
@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区的这种形式,这就是著名的荷兰国旗问题。
思路分析
设三个指针,初始化
代码实现
@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
- Leetcode - 75 - sortColors
- 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(三颜色排序→K颜色排序)
- [leetcode] 75.Sort Colors
- leetcode——75——Sort Colors
- leetcode-java-75. Sort Colors
- [LeetCode-Algorithms-75] "Sort Colors" (2017.12.7-WEEK14)