生命不息,奋斗不止
@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;
}
}
}

本文介绍了一个经典的编程问题——荷兰国旗问题。通过使用三个指针的方法,可以有效地将一个仅包含0、1、2的数组按颜色顺序排序。文章详细解释了算法思路,并提供了完整的Java代码实现。
362

被折叠的 条评论
为什么被折叠?



