您的位置:首页 > 其它

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区的这种形式,这就是著名的荷兰国旗问题。

思路分析

设三个指针,初始化
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  color leetcode 算法